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.
package/index.js CHANGED
@@ -24,8 +24,11 @@ import z from '@deepseek-ai/schemastery'
24
24
  import { selectBackend } from './lib/backend.mjs'
25
25
  import { homeDirOf } from './lib/cache.mjs'
26
26
  import { DailyService } from './lib/daily.mjs'
27
+ import { LikeService } from './lib/like.mjs'
27
28
  import { LyricsService } from './lib/lyrics.mjs'
28
29
  import { PlayerService, PLAYER_DEFAULTS } from './lib/player.mjs'
30
+ import { WebBackend } from './lib/web-backend.mjs'
31
+ import { ChannelRouter } from './lib/channel.mjs'
29
32
  import { mountTransport } from './lib/transport.mjs'
30
33
 
31
34
  export const name = 'cloudmusic-player'
@@ -49,6 +52,45 @@ export const Config = z.object({
49
52
  .default('cloudmusic|netease|wangyi')
50
53
  .description('系统媒体会话的 AppUserModelId 正则。商店/UWP 版可能要改成 CloudMusic.exe 之类,用 /health?deep=1 查'),
51
54
 
55
+ // ── 播放通道 ────────────────────────────────────────────────────────────
56
+ // k65:客户端没装/没开时,用 ego 浏览器驱动网易云网页版跑同样的 action。
57
+ // 默认「客户端优先」——客户端在线时行为完全不变;探测到助手不可用时自动切网页。
58
+ channelMode: z
59
+ .union([z.const('client-first'), z.const('web-first'), z.const('client-only'), z.const('web-only')])
60
+ .default('client-first')
61
+ .description('播放通道:client-first=客户端优先(默认,掉线自动切网页)/ web-first=网页优先 / client-only=仅客户端 / web-only=仅网页版')
62
+ .volatile(),
63
+ webBrowserJson: z
64
+ .string()
65
+ .default('')
66
+ .description('ego 浏览器 browser.json 路径。留空 = 自动(Windows 用 %LOCALAPPDATA%\\ego-lite-linux\\browser.json)'),
67
+ webLoginCookie: z
68
+ .string()
69
+ .default('')
70
+ .description('网页版登录 cookie(Cookie 头原文)。留空 = 自动复用客户端解出的 cookie 或浏览器已登录会话'),
71
+ webAutoInjectCookie: z
72
+ .boolean()
73
+ .default(true)
74
+ .description('自动把客户端解出的登录 cookie 注入 ego 浏览器,复用登录态(默认开)')
75
+ .volatile(),
76
+ webSongUrlLevel: z
77
+ .union([z.const('standard'), z.const('exhigh'), z.const('lossless'), z.const('hires')])
78
+ .default('standard')
79
+ .description('网页版音频质量(standard/exhigh/lossless/hires)。无损需 VIP,拿不到会自动降级'),
80
+
81
+ // k65 补:网页版走系统媒体会话(SMTC)识别/控制个人浏览器正在放的歌。
82
+ // ego-lite 网页是「去客户端播放」占位、用户真正在放的浏览器没有 CDP 端口——
83
+ // SMTC 是唯一能读到那首歌的公共通道。默认开;关掉则只走 CDP。
84
+ smtcEnabled: z
85
+ .boolean()
86
+ .default(true)
87
+ .description('网页版通道用系统媒体会话(SMTC)识别/控制个人浏览器正在放的歌(默认开)')
88
+ .volatile(),
89
+ smtcBrowserAumid: z
90
+ .string()
91
+ .default('msedge\\.exe|chrome\\.exe|firefox\\.exe|MSWebView2|msedgewebview2')
92
+ .description('SMTC 命中的浏览器进程 AUMID 正则。留空 = 用默认的 Edge/Chrome/Firefox/WebView2 白名单'),
93
+
52
94
  // ── 音量 ────────────────────────────────────────────────────────────────
53
95
  volumeScope: z
54
96
  .union([z.const('process'), z.const('system')])
@@ -96,6 +138,10 @@ export const Config = z.object({
96
138
  .string()
97
139
  .default('Ctrl+Alt+Left')
98
140
  .description('上一首的全局快捷键'),
141
+ hotkeyLike: z
142
+ .string()
143
+ .default('Ctrl+Alt+L')
144
+ .description('喜欢/取消喜欢的全局快捷键(默认 love=Ctrl+Alt+L;在 DSH 里点红心会用它同步客户端本地红心,需与客户端设置一致)'),
99
145
 
100
146
  // ── 进度来源(客户端日志)────────────────────────────────────────────────
101
147
  // FAQ:进度条为什么能动了。网易云 3.x 不注册 SMTC,但它把播放事件写进
@@ -139,6 +185,21 @@ export const Config = z.object({
139
185
  .default('')
140
186
  .description('客户端 CEF profile 目录。留空 = 自动找 %LOCALAPPDATA%\\NetEase\\CloudMusic\\webapp* 里 Cookies 最新的那个'),
141
187
 
188
+ // ── 喜欢(红心)────────────────────────────────────────────────────────────
189
+ // 走网易云 Web API + 客户端 cookie(不投 webcmd、不弹客户端窗口)。
190
+ likeApiBase: z
191
+ .string()
192
+ .default('')
193
+ .description('喜欢接口前缀。留空 = 跟随 dailyApiBase;方便换成镜像/反代'),
194
+ likeSyncMs: z
195
+ .number()
196
+ .step(1000)
197
+ .min(2000)
198
+ .max(60000)
199
+ .default(8000)
200
+ .description('同一首歌期间同步红心状态的间隔(毫秒)。客户端日志无喜欢事件,只能轮询;越小越及时、请求越多')
201
+ .volatile(),
202
+
142
203
  // ── 助手进程 ────────────────────────────────────────────────────────────
143
204
  powershellPath: z
144
205
  .string()
@@ -170,6 +231,13 @@ export const Config = z.object({
170
231
  export const DEFAULTS = {
171
232
  processName: 'cloudmusic',
172
233
  aumidPattern: 'cloudmusic|netease|wangyi',
234
+ channelMode: 'client-first',
235
+ webBrowserJson: '',
236
+ webLoginCookie: '',
237
+ webAutoInjectCookie: true,
238
+ webSongUrlLevel: 'standard',
239
+ smtcEnabled: true,
240
+ smtcBrowserAumid: 'msedge\\.exe|chrome\\.exe|firefox\\.exe|MSWebView2|msedgewebview2',
173
241
  volumeScope: 'process',
174
242
  lyricsEnabled: true,
175
243
  lyricsTranslation: true,
@@ -180,12 +248,15 @@ export const DEFAULTS = {
180
248
  hotkeyPlayPause: 'Ctrl+Alt+P',
181
249
  hotkeyNext: 'Ctrl+Alt+Right',
182
250
  hotkeyPrev: 'Ctrl+Alt+Left',
251
+ hotkeyLike: 'Ctrl+Alt+L',
183
252
  elogEnabled: true,
184
253
  elogPath: '',
185
254
  elogPollMs: 400,
186
255
  dailyApiBase: 'https://music.163.com/api',
187
256
  dailyLimit: 50,
188
257
  dailyProfileDir: '',
258
+ likeApiBase: '',
259
+ likeSyncMs: 8000,
189
260
  requestTimeoutMs: PLAYER_DEFAULTS.requestTimeoutMs,
190
261
  restartLimit: PLAYER_DEFAULTS.restartLimit,
191
262
  }
@@ -255,6 +326,9 @@ export function apply(ctx, config) {
255
326
  const getConfig = () => ({
256
327
  ...settings,
257
328
  ...(config ?? {}),
329
+ channelMode: unwrapVolatile(config?.channelMode) ?? settings.channelMode,
330
+ webAutoInjectCookie: unwrapVolatile(config?.webAutoInjectCookie) ?? settings.webAutoInjectCookie,
331
+ smtcEnabled: unwrapVolatile(config?.smtcEnabled) ?? settings.smtcEnabled,
258
332
  volumeScope: unwrapVolatile(config?.volumeScope) ?? settings.volumeScope,
259
333
  lyricsEnabled: unwrapVolatile(config?.lyricsEnabled) ?? settings.lyricsEnabled,
260
334
  lyricsTranslation: unwrapVolatile(config?.lyricsTranslation) ?? settings.lyricsTranslation,
@@ -268,9 +342,21 @@ export function apply(ctx, config) {
268
342
  const backend = selectBackend()
269
343
  const cacheDir = homeDirOf(ctx)
270
344
  const daily = new DailyService({ getConfig, log })
271
- const player = new PlayerService({ backend, getConfig, log, daily })
345
+ const like = new LikeService({ getConfig, log })
346
+ const native = new PlayerService({ backend, getConfig, log, daily, like })
272
347
  const lyrics = new LyricsService({ getConfig }, cacheDir)
273
348
 
349
+ // k65:网页版通道。歌词/LRC 解析复用同一个 LyricsService,登录态由后端自己
350
+ // 从客户端 cookie 注入 ego 浏览器。上层只认 player(ChannelRouter),接口形状
351
+ // 与原生 PlayerService 一致,client-first 模式下客户端在线时走的路跟以前一模一样。
352
+ const web = new WebBackend({ getConfig, log, daily })
353
+ web.like = like
354
+ web.lyricsResolver = (params) => lyrics.resolve(params)
355
+ // 系统音量是 Windows 端点级、与播放通道无关:网页版通道复用 native helper 的
356
+ // 音量读写(不依赖客户端进程,独立实测可读)。这样切到 SYS 能调、也能跟随系统。
357
+ web.systemVolumeService = native
358
+ const player = new ChannelRouter({ native, web, getConfig, log })
359
+
274
360
  /** 路由最终走的是哪条车道(fetch / webserver / none),/health 会报出去 */
275
361
  let transportState = { transport: 'pending', note: '' }
276
362
 
@@ -310,6 +396,7 @@ export function apply(ctx, config) {
310
396
  const result = await player.action(action, {
311
397
  positionMs: num(body.positionMs, 0),
312
398
  value: body.value == null ? undefined : String(body.value),
399
+ like: body.like == null ? undefined : !!body.like,
313
400
  })
314
401
  return jsonResponse(result)
315
402
  }),
@@ -377,8 +464,9 @@ export function apply(ctx, config) {
377
464
  const helper = player.readyInfo()
378
465
  return jsonResponse({
379
466
  ok: true,
380
- platform: backend.platform,
381
- backend: backend.id,
467
+ platform: helper.platform || backend.platform,
468
+ backend: helper.backend || backend.id,
469
+ channel: player.active,
382
470
  transport: transportState.transport,
383
471
  transportNote: transportState.note,
384
472
  capabilities: helper.capabilities,
@@ -387,9 +475,8 @@ export function apply(ctx, config) {
387
475
  seekWindowLeak: player.windowLeak !== false,
388
476
  helper,
389
477
  lyrics: { enabled: lyrics.enabled(), base: lyrics.base() },
390
- // 日推依赖客户端登录态(cookie 从客户端 CEF profile 解出来),
391
- // 非 Windows 直接没有这条路
392
- daily: { available: backend.platform === 'win32' },
478
+ // k65:网页版和客户端都能拉日推(网页版靠注入的 cookie 走同一套 Web API)
479
+ daily: { available: backend.platform === 'win32' || player.active === 'web' },
393
480
  })
394
481
  }),
395
482
  },
@@ -462,17 +549,19 @@ export function apply(ctx, config) {
462
549
  + '看当前在放什么。还可以取当前这首歌的歌词(带时间轴,LRC 解析后的行数组)。'
463
550
  + 'play_daily 会把它切到「每日推荐」并从第一首开始播(借客户端已登录的 cookie 取日推列表)。'
464
551
  + 'set_mode 切换播放顺序(顺序/列表循环/单曲循环/随机)。'
552
+ + 'like 收藏/取消收藏当前歌曲到「我喜欢的音乐」(会同步客户端本地红心,走客户端全局热键不弹窗;失败回退 Web API,需要客户端已登录)。'
465
553
  + '客户端没开时会返回 ok:false 与提示,不抛错。',
466
554
  parameters: {
467
555
  type: 'object',
468
556
  properties: {
469
557
  action: {
470
558
  type: 'string',
471
- enum: ['status', 'play', 'pause', 'toggle', 'next', 'prev', 'seek', 'volume', 'mute', 'lyrics', 'health', 'play_daily', 'set_mode'],
559
+ enum: ['status', 'play', 'pause', 'toggle', 'next', 'prev', 'seek', 'volume', 'mute', 'lyrics', 'health', 'play_daily', 'set_mode', 'like'],
472
560
  description:
473
561
  '要做什么。status 看当前状态;volume 需要 level;mute 需要 muted;seek 需要 positionMs;'
474
562
  + 'play_daily 播放每日推荐(替换队列,从第一首开始);'
475
- + 'set_mode 切换播放顺序(value 取 cycle 列表循环 / single 单曲循环 / random 随机 / order 顺序)',
563
+ + 'set_mode 切换播放顺序(value 取 cycle 列表循环 / single 单曲循环 / random 随机 / order 顺序);'
564
+ + 'like 收藏/取消收藏当前歌曲(like 为 true 收藏、false 取消,省略则切换)',
476
565
  },
477
566
  positionMs: { type: 'integer', description: 'seek 的目标位置(毫秒)' },
478
567
  level: { type: 'number', description: 'volume 的目标音量,0..1' },
@@ -482,6 +571,10 @@ export function apply(ctx, config) {
482
571
  enum: ['cycle', 'single', 'random', 'order'],
483
572
  description: 'set_mode 的目标播放顺序:cycle 列表循环 / single 单曲循环 / random 随机 / order 顺序',
484
573
  },
574
+ like: {
575
+ type: 'boolean',
576
+ description: 'like 的目标状态:true=收藏到「我喜欢的音乐」,false=取消;省略则按当前状态切换',
577
+ },
485
578
  scope: {
486
579
  type: 'string',
487
580
  enum: ['process', 'system'],
@@ -521,16 +614,20 @@ export function apply(ctx, config) {
521
614
  // 进度来源有三种:smtc(系统给的准值)、elog(客户端日志,靠 orpheus 协议 seek)、
522
615
  // peak(峰值估算,没有时间轴)。别在 peak 状态下报一个假的 0:00 / 0:00。
523
616
  const hasTimeline = Number(n.end) > 0
524
- const src = n.positionSource === 'elog' ? '客户端日志' : n.positionSource === 'smtc' ? '系统媒体会话' : '峰值估算'
617
+ const src = n.positionSource === 'elog' ? '客户端日志' : n.positionSource === 'smtc' ? '系统媒体会话' : n.positionSource === 'smtc-web' ? '系统媒体(浏览器)' : n.positionSource === 'winrt' ? '日推后台播放' : n.positionSource === 'web' ? '网页版' : '峰值估算'
525
618
  const progress = hasTimeline
526
619
  ? `进度 ${fmt(n.pos)} / ${fmt(n.end)}(来自${src}${n.canSeek ? ',可 seek' : ',不能 seek'})`
527
620
  : `进度:${src}拿不到时间轴(无法 seek)`
528
- const lane = n.channel === 'native' ? '原生车道(窗口标题 + 音频峰值 + 客户端全局热键 + orpheus 协议 seek)' : '系统媒体会话(SMTC)'
621
+ const lane = n.channel === 'web' ? '网页版(ego 浏览器 + 在线音频)'
622
+ : n.channel === 'native' ? '原生车道(窗口标题 + 音频峰值 + 客户端全局热键 + orpheus 协议 seek)' : '系统媒体会话(SMTC)'
529
623
  return [
530
- `${status} · ${n.title || '(无标题)'}${n.artist ? ` - ${n.artist}` : ''}`,
624
+ `${status} · ${n.title || '(无标题)'}${n.artist ? ` - ${n.artist}` : ''}${n.liked === true ? ' ♥ 已喜欢' : ''}`,
531
625
  progress,
532
626
  vol,
533
627
  `通道 ${lane}`,
628
+ n.mode && { playOrder: 1, playCycle: 1, playOneCycle: 1, playRandom: 1 }[n.mode]
629
+ ? `播放顺序 ${{ playOrder: '顺序', playCycle: '列表循环', playOneCycle: '单曲循环', playRandom: '随机' }[n.mode]}`
630
+ : '',
534
631
  ].filter(Boolean).join('\n')
535
632
  }
536
633
 
@@ -542,6 +639,7 @@ export function apply(ctx, config) {
542
639
  const h = await player.deepHealth()
543
640
  return {
544
641
  text: [
642
+ `当前通道 ${h.channel || player.active}${h.loggedIn !== undefined ? ` · 网页登录 ${h.loggedIn ? '已登录' : '未登录'}` : ''}`,
545
643
  `平台 ${h.platform} · 后端 ${h.backend} · PowerShell ${h.ps || '?'} · WinRT ${h.winrt ? 'ok' : '不可用'} · 窗口 ${h.window ? 'ok' : '不可用'}`,
546
644
  `进程 ${(h.pids || []).join(', ') || '(无)'} · 目标会话 ${h.target || '(SMTC 未匹配,走原生车道)'}`,
547
645
  `媒体会话:${(h.media || []).map((m) => `${m.aumid}${m.title ? `(${m.title})` : ''}`).join(' / ') || '(无)'}`,
@@ -615,6 +713,11 @@ export function apply(ctx, config) {
615
713
  if (!res.ok) return { text: `切换播放顺序失败:${res.message || res.error || 'unknown'}${res.detail ? ` (${res.detail})` : ''}` }
616
714
  return { text: `播放顺序已切到 ${labels[value]}。` }
617
715
  }
716
+ if (action === 'like') {
717
+ const res = await player.action('like', { like: args?.like })
718
+ if (!res.ok) return { text: `${res.message || '操作失败'}(${res.error || 'unknown'}${res.detail ? `, ${res.detail}` : ''})` }
719
+ return { text: `${res.liked ? '已收藏到「我喜欢的音乐」' : '已取消喜欢'}。${describe({ ok: true, now: res.now, volume: res.volume })}` }
720
+ }
618
721
  const res = await player.action(action, { positionMs: num(args?.positionMs, 0) })
619
722
  if (!res.ok) {
620
723
  return { text: `操作失败:${res.error || 'unknown'}${res.detail ? ` (${res.detail})` : ''}` }
package/lib/backend.mjs CHANGED
@@ -64,7 +64,7 @@ function resolvePowershell(configured) {
64
64
  * @property {(cfg: object) => { shell: string, args: string[] }} command
65
65
  */
66
66
 
67
- /** @typedef {{ processName: string, aumidPattern: string, powershellPath: string, helperPath: string, hotkeyPlayPause?: string, hotkeyNext?: string, hotkeyPrev?: string }} HelperConfig */
67
+ /** @typedef {{ processName: string, aumidPattern: string, powershellPath: string, helperPath: string, hotkeyPlayPause?: string, hotkeyNext?: string, hotkeyPrev?: string, hotkeyLike?: string }} HelperConfig */
68
68
 
69
69
  /** Windows:常驻 powershell.exe + lib/helper.ps1 */
70
70
  export const windowsBackend = {
@@ -76,7 +76,7 @@ export const windowsBackend = {
76
76
  * 组装 spawn 参数。`helperPath` 配置优先于包内脚本,
77
77
  * 方便高阶用户把脚本拷出去改(但默认不需要)。
78
78
  *
79
- * 三个热键参数是给 native 车道用的:客户端注册 SMTC 失败时,
79
+ * 四个热键参数(含喜欢)是给 native 车道用的:客户端注册 SMTC 失败时,
80
80
  * 只能靠它自己的全局快捷键来控制播放,所以组合键必须和客户端里一致。
81
81
  * @param {HelperConfig} cfg
82
82
  */
@@ -98,6 +98,7 @@ export const windowsBackend = {
98
98
  if (cfg.hotkeyPlayPause) args.push('-HotkeyPlayPause', String(cfg.hotkeyPlayPause))
99
99
  if (cfg.hotkeyNext) args.push('-HotkeyNext', String(cfg.hotkeyNext))
100
100
  if (cfg.hotkeyPrev) args.push('-HotkeyPrev', String(cfg.hotkeyPrev))
101
+ if (cfg.hotkeyLike) args.push('-HotkeyLike', String(cfg.hotkeyLike))
101
102
  return { shell: resolvePowershell(cfg.powershellPath), args }
102
103
  },
103
104
  }
@@ -0,0 +1,229 @@
1
+ /**
2
+ * channel.mjs — 播放通道选择器(k65)
3
+ *
4
+ * 在原有 native(客户端)通道之外,加一条 web(网页版)通道。对上层(index.js
5
+ * 的 6 条路由 + cloudmusic_player 工具)暴露与 PlayerService 完全一致的形状,
6
+ * 调用方无需知道当前是哪条通道在干活。
7
+ *
8
+ * 四种模式(Config.channelMode,默认 client-first):
9
+ * client-only : 永远走 native,行为与 k65 之前完全一致;
10
+ * web-only : 永远走 web;
11
+ * client-first: 客户端进程在 → native(不变);不在 → web;
12
+ * web-first : web 可用(浏览器通 + 已登录)→ web;否则 → native。
13
+ *
14
+ * 「客户端在线」的判据是进程是否存在,而不是 helper 是否 ready——helper 是
15
+ * powershell,客户端没开它也能起来,只是没会话;按进程判才能避免「开着客户端
16
+ * 没播歌」被误判成离线。
17
+ */
18
+
19
+ import { execFile } from 'node:child_process'
20
+ import { promisify } from 'node:util'
21
+
22
+ const execFileAsync = promisify(execFile)
23
+ const CLIENT_CHECK_MS = 3000
24
+ const PLAYING_CHECK_MS = 1500
25
+
26
+ /** 探测网易云客户端进程是否存在。非 Windows 视为无客户端。 */
27
+ export async function detectClientRunning(cfg = {}) {
28
+ if (process.platform !== 'win32') return false
29
+ const names = new Set(['cloudmusic', 'neteasecloudmusic', 'netease cloud music'])
30
+ const pn = String(cfg.processName || '').toLowerCase().replace(/\.exe$/, '')
31
+ if (pn) names.add(pn)
32
+ try {
33
+ // 用绝对路径:DSH 宿主进程的 PATH 未必含 System32,裸 'tasklist' 会 ENOENT
34
+ // 落进 catch。独立脚本能跑只因 shell 补了 PATH——这正是「诊断脚本对、运行时错」的根源。
35
+ const tasklist = `${process.env.SystemRoot || 'C:\\Windows'}\\System32\\tasklist.exe`
36
+ const { stdout } = await execFileAsync(tasklist, ['/FO', 'CSV', '/NH'], {
37
+ timeout: 3000,
38
+ windowsHide: true,
39
+ maxBuffer: 4 * 1024 * 1024,
40
+ })
41
+ const lower = stdout.toLowerCase()
42
+ for (const n of names) {
43
+ if (lower.includes(`${n}.exe`)) return true
44
+ }
45
+ return false
46
+ } catch {
47
+ // tasklist 在宿主运行时里可能因 cwd/PATH 差异失败(独立脚本却正常)。
48
+ // 以前这里 return true(判客户端在线),会让 client-first 兜底误选 native,
49
+ // 于是「网页版正在放歌」被显示成已暂停·无标题。现在 pick() 已有 channelPlaying
50
+ // 前置判据——客户端真在播会优先选 native,所以探测失败时判「不在」更安全:
51
+ // 网页在播能切过去,都没播则走 web 便于插件起播。
52
+ return false
53
+ }
54
+ }
55
+
56
+ export class ChannelRouter {
57
+ /**
58
+ * @param {{ native: any, web: import('./web-backend.mjs').WebBackend,
59
+ * getConfig: () => any, log?: (msg:string)=>void }} deps
60
+ */
61
+ constructor({ native, web, getConfig, log = () => {} }) {
62
+ this.native = native
63
+ this.web = web
64
+ this.getConfig = getConfig
65
+ this.log = log
66
+ this.active = 'native'
67
+ this._clientCache = { at: 0, value: null }
68
+ this._webCache = { at: 0, value: null }
69
+ this._playingCache = { native: { at: 0, value: false }, web: { at: 0, value: false } }
70
+ }
71
+
72
+ mode() { return this.getConfig().channelMode || 'client-first' }
73
+
74
+ async clientOnline() {
75
+ const now = Date.now()
76
+ if (this._clientCache.value !== null && now - this._clientCache.at < CLIENT_CHECK_MS) {
77
+ return this._clientCache.value
78
+ }
79
+ const value = await detectClientRunning(this.getConfig())
80
+ this._clientCache = { at: now, value }
81
+ return value
82
+ }
83
+
84
+ async webAvailable() {
85
+ const now = Date.now()
86
+ if (this._webCache.value !== null && now - this._webCache.at < CLIENT_CHECK_MS) {
87
+ return this._webCache.value
88
+ }
89
+ let value = false
90
+ try {
91
+ const ready = await this.web.ensure()
92
+ value = ready.ok !== false && await this.web._isLoggedIn().catch(() => false)
93
+ } catch { value = false }
94
+ this._webCache = { at: now, value }
95
+ return value
96
+ }
97
+
98
+ /**
99
+ * 判定某条通道当前是否真的在放歌。判据:state 拿到 now 且 status=Playing
100
+ * 且有有效标题(不是 (无标题)/网易云音乐 占位)。带短缓存,避免每次轮询连 CDP。
101
+ */
102
+ async channelPlaying(ch) {
103
+ const cache = this._playingCache[ch]
104
+ const now = Date.now()
105
+ if (cache.value && now - cache.at < PLAYING_CHECK_MS) return true
106
+ let playing = false
107
+ try {
108
+ const st = ch === 'web' ? await this.web.state() : await this.native.state({ fresh: true })
109
+ const n = st?.now
110
+ const title = String(n?.title || '').trim()
111
+ const validTitle = title && title !== '(无标题)' && title !== '网易云音乐' && title !== '无标题'
112
+ playing = !!(st?.ok !== false && n && validTitle && (
113
+ n.status === 'Playing' || n.status === 'playing' || n.playing === true
114
+ ))
115
+ } catch { playing = false }
116
+ this._playingCache[ch] = { at: now, value: playing }
117
+ return playing
118
+ }
119
+
120
+ /** 选定本次调用走哪条通道,并记到 this.active(供 health/describe 报告)。
121
+ * client-first / web-first 都先看「谁真的在播」,谁在播跟谁;都没播才按可用性兜底。 */
122
+ async pick() {
123
+ const m = this.mode()
124
+ let chosen
125
+ switch (m) {
126
+ case 'client-only':
127
+ chosen = 'native'; break
128
+ case 'web-only':
129
+ chosen = 'web'; break
130
+ case 'web-first':
131
+ if (await this.channelPlaying('web')) chosen = 'web'
132
+ else if (await this.channelPlaying('native')) chosen = 'native'
133
+ else chosen = (await this.webAvailable()) ? 'web' : 'native'
134
+ break
135
+ case 'client-first':
136
+ default:
137
+ if (await this.channelPlaying('native')) chosen = 'native'
138
+ else if (await this.channelPlaying('web')) chosen = 'web'
139
+ else chosen = (await this.clientOnline()) ? 'native' : 'web'
140
+ break
141
+ }
142
+ if (chosen !== this.active) {
143
+ this.log(`播放通道切换:${this.active} → ${chosen}(模式 ${m})`)
144
+ this.active = chosen
145
+ }
146
+ return chosen
147
+ }
148
+
149
+ get backend() { return this.active === 'web' ? this.web : this.native.backend }
150
+ get degraded() { return this.active === 'web' ? (this.web.lastError || '') : (this.native.degraded || '') }
151
+ get windowLeak() { return this.active === 'web' ? false : this.native.windowLeak }
152
+ get ready() { return this.active === 'web' ? true : this.native.ready }
153
+ get restartLimit() { return this.native.restartLimit }
154
+
155
+ on(...args) { return this.native.on(...args) }
156
+ start(...args) { return this.native.start(...args) }
157
+
158
+ async state(opts = {}) {
159
+ const ch = await this.pick()
160
+ if (ch === 'web') return this.web.state()
161
+ return this.native.state(opts)
162
+ }
163
+
164
+ async action(action, extra = {}) {
165
+ const ch = await this.pick()
166
+ if (ch === 'web') return this.web.action(action, extra)
167
+ return this.native.action(action, extra)
168
+ }
169
+
170
+ async volume(opts = {}) {
171
+ const ch = await this.pick()
172
+ if (ch === 'web') return this.web.volume(opts)
173
+ return this.native.volume(opts)
174
+ }
175
+
176
+ readyInfo() {
177
+ if (this.active === 'web') {
178
+ return {
179
+ healthy: true,
180
+ ready: true,
181
+ backend: this.web.id,
182
+ platform: 'web',
183
+ capabilities: this.web.capabilities,
184
+ degraded: this.web.lastError || '',
185
+ }
186
+ }
187
+ return this.native.readyInfo()
188
+ }
189
+
190
+ async restart() {
191
+ // 重启的是 native 助手进程;web 通道没进程可重启,ensure 会自愈。
192
+ if (this.active === 'web') {
193
+ this.web.stop()
194
+ return { backend: this.web.id, note: '网页版通道已重连' }
195
+ }
196
+ return this.native.restart()
197
+ }
198
+
199
+ async deepHealth() {
200
+ const ch = await this.pick()
201
+ if (ch === 'web') {
202
+ const h = await this.web.deepHealth()
203
+ return {
204
+ ...h,
205
+ channel: 'web',
206
+ channels: {
207
+ native: { backend: this.native.backend.id, platform: this.native.backend.platform, degraded: this.native.degraded || '' },
208
+ web: { backend: this.web.id, platform: 'web', reachable: h.ok !== false },
209
+ },
210
+ }
211
+ }
212
+ const h = await this.native.deepHealth()
213
+ return {
214
+ ...h,
215
+ channel: 'native',
216
+ channels: {
217
+ native: { backend: this.native.backend.id, platform: this.native.backend.platform, degraded: this.native.degraded || '' },
218
+ web: { backend: this.web.id, platform: 'web', reachable: await this.webAvailable() },
219
+ },
220
+ }
221
+ }
222
+
223
+ stop() {
224
+ try { this.native.stop() } catch { /* ignore */ }
225
+ try { this.web.stop() } catch { /* ignore */ }
226
+ }
227
+ }
228
+
229
+ export default ChannelRouter
package/lib/elog.mjs CHANGED
@@ -215,6 +215,37 @@ function unescapeJson(str) {
215
215
  }
216
216
  }
217
217
 
218
+ /**
219
+ * 从一条播放事件的顶层对象里抠出「歌曲来源」。
220
+ *
221
+ * 网易云客户端大卡片上的「来源:xxx」显示的是 `playing.curPlaying.text`
222
+ * (app.chunk 的 TrackInfoContainer:`来源:` + f.text,空则「未知」)。
223
+ * 这三个字段(scene/href/text)是**顶层**键,排在 `"localTrack"` 之前;
224
+ * 日志里 `"localTrack":{}` 之后是完整 track,里面可能有同名字段。
225
+ * 所以先截到 `"localTrack"` 再取,避免抓到 track 内部的值。
226
+ *
227
+ * 数据来源有两类,形状相同:
228
+ * 1. `playOneTrackInPlayingList` / `checkPlayPrivilege` —— 每次切歌必发,
229
+ * 顶层就带 scene/href/text(主用,实测 `text` 就是客户端显示值);
230
+ * 2. `refreshCurPlaying` —— curPlaying 顶层也带,但它极稀疏(翻列表才发),
231
+ * 只作兜底。
232
+ *
233
+ * 同样**不用 JSON.parse**:这些行可能被截断(checkPlayPrivilege 尤其明显)。
234
+ *
235
+ * @param {string} text
236
+ * @returns {{scene:string,href:string,text:string}|null}
237
+ */
238
+ export function extractSource(text) {
239
+ if (typeof text !== 'string') return null
240
+ const cut = text.indexOf('"localTrack"')
241
+ const head = cut > 0 ? text.slice(0, cut) : text.slice(0, 600)
242
+ const scene = firstString(head, 'scene')
243
+ const href = firstString(head, 'href')
244
+ const srcText = firstString(head, 'text')
245
+ if (!scene && !href && !srcText) return null
246
+ return { scene, href, text: unescapeJson(srcText) }
247
+ }
248
+
218
249
  // ---------------------------------------------------------------------------
219
250
  // 事件分类
220
251
  // ---------------------------------------------------------------------------
@@ -343,6 +374,13 @@ export class ElogWatcher {
343
374
  /** @type {{songId:string,title:string,artist:string,album:string,durationMs:number}|null} */
344
375
  this.track = null
345
376
  this.songId = ''
377
+ /**
378
+ * 当前播放上下文的「来源」(客户端大卡片「来源:xxx」)。
379
+ * 来自 refreshCurPlaying 事件的 curPlaying.top-level {scene,href,text};
380
+ * 空 text 表示客户端显示「未知」。只保留 last-known,不随每次切歌清掉。
381
+ * @type {{scene:string,href:string,text:string}|null}
382
+ */
383
+ this.source = null
346
384
  /** 锚点:{ at: 事件时间戳, positionMs } */
347
385
  this.anchor = null
348
386
  /**
@@ -569,7 +607,13 @@ export class ElogWatcher {
569
607
  #apply(ev, rest, t) {
570
608
  switch (ev.type) {
571
609
  case 'track': {
572
- const raw = extractTrack(rest.slice(rest.indexOf('{')))
610
+ const json = rest.slice(rest.indexOf('{'))
611
+ // 每次切歌必发的 playOneTrackInPlayingList 顶层就带来源(scene/href/text),
612
+ // 这才是客户端「来源:xxx」的主数据源。refreshCurPlaying 太稀疏(翻列表才发),
613
+ // 且常落在回放切点之前被跳过,靠它拿不到来源。抽不到时保留 last-known。
614
+ const src = extractSource(json)
615
+ if (src) this.source = src
616
+ const raw = extractTrack(json)
573
617
  if (!raw) return
574
618
  const track = {
575
619
  songId: raw.songId,
@@ -599,6 +643,12 @@ export class ElogWatcher {
599
643
  // 'track' 那样把 anchor 重置成 0 —— 那会让进度莫名其妙跳回开头,
600
644
  // 也不能直接换掉 this.track(新歌详情可能比 started 早 3~28 秒到,
601
645
  // 那段时间旧歌还在播,换了就会「歌名是新的、进度是旧的」)。
646
+ // refreshCurPlaying 还带 curPlaying 顶层的来源(scene/href/text),
647
+ // 顺手记下来作 last-known —— 这才是客户端「来源:xxx」显示的那串字。
648
+ if (rest.indexOf(MARK_META_CUR) >= 0) {
649
+ const src = extractSource(rest.slice(rest.indexOf('{')))
650
+ if (src) this.source = src
651
+ }
602
652
  const raw = extractTrack(rest.slice(rest.indexOf('{')))
603
653
  if (!raw) return
604
654
  const meta = {
@@ -798,6 +848,7 @@ export class ElogWatcher {
798
848
  positionMs: track ? Math.round(this.#positionAt(nowMs)) : 0,
799
849
  durationMs,
800
850
  songId: track ? track.songId : '',
851
+ source: this.source,
801
852
  mode: this.mode,
802
853
  lastEventAt: this.lastEventAt,
803
854
  reason: this.reason,
@@ -819,6 +870,7 @@ export class ElogWatcher {
819
870
  appPid: this.appPid,
820
871
  songId: this.songId,
821
872
  track: this.track,
873
+ source: this.source,
822
874
  mode: this.mode,
823
875
  playing: !this.pausing && !this.ended,
824
876
  anchorAt: this.anchor ? this.anchor.at : 0,