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,632 @@
1
+ /**
2
+ * test/like.test.mjs —— lib/like.mjs(红心)+ player 的 like 分支
3
+ * ============================================================================
4
+ * 跑法:node --test test/like.test.mjs
5
+ *
6
+ * 全部离线:cookie 解密与网络都打桩,不碰真机 CEF profile、不打真接口。
7
+ *
8
+ * 盯住几条容易回归的行为:
9
+ * 1. csrfOf / normalizeLiked 认得网易云那几种返回形状(含 check 的命中 id 列表);
10
+ * 2. isLiked 打 /song/like/check 带 trackIds,按 songId 缓存 60s,同 id 查询 in-flight 合并;
11
+ * 3. setLiked 写对 form 字段(trackId/like/csrf_token),成功后写缓存;
12
+ * 4. 未登录 / 网络异常各走各的错误码;
13
+ * 5. PlayerService.action('like') 用 elog 的 songId、回填 liked。
14
+ * ============================================================================
15
+ */
16
+ import { test } from 'node:test'
17
+ import assert from 'node:assert/strict'
18
+
19
+ import { LikeService, csrfOf, normalizeLiked, classifyLikeError, DEFAULT_API_BASE } from '../lib/like.mjs'
20
+ import { PlayerService } from '../lib/player.mjs'
21
+
22
+ const OK_COOKIE = { ok: true, cookie: 'MUSIC_U=abc; __csrf=tok42', uid: '42', profileDir: 'X' }
23
+
24
+ /** 打桩 fetchJson:记录调用,按顺序回放 */
25
+ function stubFetch(script) {
26
+ const calls = []
27
+ let i = 0
28
+ const fn = async (url, fields, opts) => {
29
+ calls.push({ url, fields, opts })
30
+ const step = script[Math.min(i, script.length - 1)]
31
+ i += 1
32
+ if (typeof step === 'function') return await step(url, fields, opts)
33
+ if (step instanceof Error) throw step
34
+ return step
35
+ }
36
+ fn.calls = calls
37
+ return fn
38
+ }
39
+
40
+ /** 固定时钟,方便测 60s 缓存 */
41
+ function svc({ fetchJson, cookie = OK_COOKIE, getConfig = () => ({}), log } = {}) {
42
+ let clock = 1_000_000
43
+ const s = new LikeService({
44
+ getConfig,
45
+ log: log || (() => {}),
46
+ cookieLoader: async () => (typeof cookie === 'function' ? cookie() : cookie),
47
+ fetchJson: fetchJson || stubFetch([]),
48
+ now: () => clock,
49
+ })
50
+ s.__advance = (ms) => (clock += ms)
51
+ return s
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // 纯函数
56
+ // ---------------------------------------------------------------------------
57
+
58
+ test('csrfOf 从 cookie 串里取 __csrf(含 URL 编码)', () => {
59
+ assert.equal(csrfOf('MUSIC_U=abc; __csrf=tok42'), 'tok42')
60
+ assert.equal(csrfOf('__csrf=a%2Bb; other=1'), 'a+b')
61
+ assert.equal(csrfOf('MUSIC_U=abc'), '')
62
+ assert.equal(csrfOf(''), '')
63
+ })
64
+
65
+ test('classifyLikeError 把下架歌的 401 和真需要登录的 401 分开', () => {
66
+ // 下架/版权类 401 → 新错误码,不再误报 like-needs-login(前端会硬映射成「请先登录客户端」)
67
+ assert.equal(classifyLikeError(401, '下架歌曲无法收藏'), 'like-unavailable-song')
68
+ assert.equal(classifyLikeError(401, '该歌曲版权受限,无法收藏'), 'like-unavailable-song')
69
+ assert.equal(classifyLikeError(301, '歌曲已下线'), 'like-unavailable-song')
70
+ assert.equal(classifyLikeError(401, 'This song is unavailable'), 'like-unavailable-song')
71
+ // 真正的需要登录 → 保留 like-needs-login
72
+ assert.equal(classifyLikeError(401, '需要登录'), 'like-needs-login')
73
+ assert.equal(classifyLikeError(301, ''), 'like-needs-login')
74
+ assert.equal(classifyLikeError(401), 'like-needs-login')
75
+ // 非 301/401 → like-failed
76
+ assert.equal(classifyLikeError(500, '下架歌曲无法收藏'), 'like-failed')
77
+ assert.equal(classifyLikeError(200), 'like-failed')
78
+ })
79
+
80
+ test('normalizeLiked 认得 map / 数组 / 布尔多种形状', () => {
81
+ assert.equal(normalizeLiked({ songs: { '123': true, '456': false } }, 123), true)
82
+ assert.equal(normalizeLiked({ songs: { '123': true } }, '123'), true)
83
+ assert.equal(normalizeLiked({ data: { '456': false } }, 456), false)
84
+ assert.equal(normalizeLiked({ songs: [{ id: 123, liked: true }] }, 123), true)
85
+ assert.equal(normalizeLiked({ data: [{ songId: '456', starred: 1 }] }, 456), true)
86
+ assert.equal(normalizeLiked({ liked: false }, 999), false)
87
+ assert.equal(normalizeLiked({ songs: { '123': true } }, 999), null)
88
+ assert.equal(normalizeLiked({}, 123), null)
89
+ assert.equal(normalizeLiked({ songs: { '123': 1 } }, 123), true)
90
+ assert.equal(normalizeLiked({ songs: { '123': 'false' } }, 123), false)
91
+ })
92
+
93
+ test('normalizeLiked 认得 /song/like/check 的命中 id 数组(主用形状)', () => {
94
+ // check 只返回已喜欢的 id:命中 true,不在数组里 false,空数组 false
95
+ assert.equal(normalizeLiked({ ids: [1859245776, 999], code: 200 }, 1859245776), true)
96
+ assert.equal(normalizeLiked({ ids: [1859245776, 999], code: 200 }, 12345), false)
97
+ assert.equal(normalizeLiked({ ids: ['1859245776'], code: 200 }, '1859245776'), true)
98
+ assert.equal(normalizeLiked({ ids: [], code: 200 }, 1859245776), false)
99
+ // 大 id 以字符串传入时按原样比对,不能被 Number 精度改写
100
+ assert.equal(normalizeLiked({ ids: ['9007199254740993'], code: 200 }, '9007199254740993'), true)
101
+ })
102
+
103
+ test('DEFAULT_API_BASE 是网易云接口前缀', () => {
104
+ assert.equal(DEFAULT_API_BASE, 'https://music.163.com/api')
105
+ })
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // LikeService.isLiked
109
+ // ---------------------------------------------------------------------------
110
+
111
+ test('isLiked 打 /song/like/check,带 trackIds 与 csrf_token,并写缓存', async () => {
112
+ const fetchJson = stubFetch([{ code: 200, ids: [123] }])
113
+ const s = svc({ fetchJson })
114
+ const res = await s.isLiked(123)
115
+ assert.deepEqual(res, { ok: true, liked: true, cached: false })
116
+ assert.equal(fetchJson.calls.length, 1)
117
+ assert.equal(fetchJson.calls[0].url, `${DEFAULT_API_BASE}/song/like/check`)
118
+ assert.equal(fetchJson.calls[0].fields.trackIds, '["123"]')
119
+ assert.equal(fetchJson.calls[0].fields.csrf_token, 'tok42')
120
+ assert.equal(fetchJson.calls[0].opts.cookie, OK_COOKIE.cookie)
121
+ // 第二次命中缓存,不发请求
122
+ const again = await s.isLiked(123)
123
+ assert.equal(again.cached, true)
124
+ assert.equal(fetchJson.calls.length, 1)
125
+ })
126
+
127
+ test('isLiked 端到端回放:check 命中列表决定 liked,空列表即未喜欢', async () => {
128
+ const f1 = stubFetch([{ ids: [1859245776], code: 200 }])
129
+ assert.deepEqual(await svc({ fetchJson: f1 }).isLiked(1859245776), { ok: true, liked: true, cached: false })
130
+ const f2 = stubFetch([{ ids: [], code: 200 }])
131
+ assert.deepEqual(await svc({ fetchJson: f2 }).isLiked(12345), { ok: true, liked: false, cached: false })
132
+ // 大 id 走字符串原样,不被 Number 截断
133
+ const f3 = stubFetch([{ ids: ['9007199254740993'], code: 200 }])
134
+ assert.deepEqual(await svc({ fetchJson: f3 }).isLiked('9007199254740993'), { ok: true, liked: true, cached: false })
135
+ assert.equal(f3.calls[0].fields.trackIds, '["9007199254740993"]')
136
+ })
137
+
138
+ test('isLiked 60 秒后过期重查;force 强制重查', async () => {
139
+ const fetchJson = stubFetch([{ code: 200, ids: [1] }, { code: 200, ids: [] }])
140
+ const s = svc({ fetchJson })
141
+ await s.isLiked(1)
142
+ await s.isLiked(1) // 缓存
143
+ assert.equal(fetchJson.calls.length, 1)
144
+ s.__advance(61_000)
145
+ const res = await s.isLiked(1)
146
+ assert.equal(res.liked, false)
147
+ assert.equal(fetchJson.calls.length, 2)
148
+ await s.isLiked(1, { force: true })
149
+ assert.equal(fetchJson.calls.length, 3)
150
+ })
151
+
152
+ test('isLiked 同 id 并发只读一次(in-flight 合并)', async () => {
153
+ let release
154
+ const gate = new Promise((r) => (release = r))
155
+ const fetchJson = stubFetch([async () => (await gate, { code: 200, ids: [7] })])
156
+ const s = svc({ fetchJson })
157
+ const p1 = s.isLiked(7)
158
+ const p2 = s.isLiked(7)
159
+ release()
160
+ const [a, b] = await Promise.all([p1, p2])
161
+ assert.equal(a.liked, true)
162
+ assert.equal(b.liked, true)
163
+ assert.equal(fetchJson.calls.length, 1)
164
+ })
165
+
166
+ test('isLiked 无 songId 直接 like-no-song,不打接口', async () => {
167
+ const fetchJson = stubFetch([])
168
+ const s = svc({ fetchJson })
169
+ for (const id of ['', '0', null]) {
170
+ const res = await s.isLiked(id)
171
+ assert.equal(res.ok, false)
172
+ assert.equal(res.error, 'like-no-song')
173
+ }
174
+ assert.equal(fetchJson.calls.length, 0)
175
+ })
176
+
177
+ test('isLiked 未登录(code 301)翻成 like-needs-login', async () => {
178
+ const s = svc({ fetchJson: stubFetch([{ code: 301 }]) })
179
+ const res = await s.isLiked(1)
180
+ assert.equal(res.ok, false)
181
+ assert.equal(res.error, 'like-needs-login')
182
+ })
183
+
184
+ test('isLiked 其它非零 code 翻成 like-failed', async () => {
185
+ const s = svc({ fetchJson: stubFetch([{ code: 500 }]) })
186
+ const res = await s.isLiked(1)
187
+ assert.equal(res.error, 'like-failed')
188
+ })
189
+
190
+ test('isLiked 网络异常 / 401 走不同错误码', async () => {
191
+ const e = new Error('boom')
192
+ e.status = 500
193
+ const s1 = svc({ fetchJson: stubFetch([e]) })
194
+ assert.equal((await s1.isLiked(1)).error, 'like-network')
195
+ const e2 = new Error('unauthorized')
196
+ e2.status = 401
197
+ const s2 = svc({ fetchJson: stubFetch([e2]) })
198
+ assert.equal((await s2.isLiked(1)).error, 'like-needs-login')
199
+ })
200
+
201
+ test('isLiked 读不到登录凭证时返回 like-needs-login / like-unavailable', async () => {
202
+ const s1 = svc({ fetchJson: stubFetch([]), cookie: () => ({ ok: false }) })
203
+ assert.equal((await s1.isLiked(1)).error, 'like-needs-login')
204
+ const s2 = svc({ fetchJson: stubFetch([]), cookie: () => ({ ok: false, error: 'cookie-unsupported' }) })
205
+ assert.equal((await s2.isLiked(1)).error, 'like-unavailable')
206
+ const s3 = svc({ fetchJson: stubFetch([]), cookie: () => { throw new Error('fs') } })
207
+ assert.equal((await s3.isLiked(1)).error, 'like-no-cookie')
208
+ })
209
+
210
+ test('isLiked 读不认识的返回形状报 like-failed', async () => {
211
+ const s = svc({ fetchJson: stubFetch([{ code: 200, nope: 1 }]) })
212
+ assert.equal((await s.isLiked(1)).error, 'like-failed')
213
+ })
214
+
215
+ // ---------------------------------------------------------------------------
216
+ // LikeService.setLiked
217
+ // ---------------------------------------------------------------------------
218
+
219
+ test('setLiked 写对 form 字段并写缓存(收藏)', async () => {
220
+ const fetchJson = stubFetch([{ code: 200 }])
221
+ const s = svc({ fetchJson })
222
+ const res = await s.setLiked(123, true)
223
+ assert.deepEqual(res, { ok: true, liked: true })
224
+ assert.equal(fetchJson.calls[0].url, `${DEFAULT_API_BASE}/song/like`)
225
+ assert.equal(fetchJson.calls[0].fields.trackId, '123')
226
+ assert.equal(fetchJson.calls[0].fields.like, 'true')
227
+ assert.equal(fetchJson.calls[0].fields.csrf_token, 'tok42')
228
+ // songid 是错的旧参数名(会返回 code 400),绝不能回归
229
+ assert.equal(fetchJson.calls[0].fields.songid, undefined)
230
+ assert.equal(s.cache.get('123').liked, true)
231
+ })
232
+
233
+ test('setLiked(false) 取消收藏,like 字段是 false 字符串', async () => {
234
+ const fetchJson = stubFetch([{ code: 200 }])
235
+ const s = svc({ fetchJson })
236
+ await s.setLiked(123, false)
237
+ assert.equal(fetchJson.calls[0].fields.like, 'false')
238
+ assert.equal(s.cache.get('123').liked, false)
239
+ })
240
+
241
+ test('setLiked/isLiked 下架歌曲 401 → like-unavailable-song(不再误报 needs-login)', async () => {
242
+ const s1 = svc({ fetchJson: stubFetch([{ code: 401, message: '下架歌曲无法收藏' }]) })
243
+ const r1 = await s1.setLiked(9, true)
244
+ assert.equal(r1.ok, false)
245
+ assert.equal(r1.error, 'like-unavailable-song')
246
+ assert.match(r1.message, /下架/)
247
+ const s2 = svc({ fetchJson: stubFetch([{ code: 401, message: '下架歌曲无法收藏' }]) })
248
+ const r2 = await s2.isLiked(9)
249
+ assert.equal(r2.error, 'like-unavailable-song')
250
+ // 真「需要登录」的 401 仍保留 needs-login,原生通道真未登录照常提示
251
+ const s3 = svc({ fetchJson: stubFetch([{ code: 401, message: '需要登录' }]) })
252
+ assert.equal((await s3.setLiked(9, true)).error, 'like-needs-login')
253
+ })
254
+
255
+ test('setLiked 失败时不动缓存', async () => {
256
+ const s = svc({ fetchJson: stubFetch([{ code: 500 }]) })
257
+ const res = await s.setLiked(9, true)
258
+ assert.equal(res.ok, false)
259
+ assert.equal(res.error, 'like-failed')
260
+ assert.equal(s.cache.has('9'), false)
261
+ })
262
+
263
+ test('setLiked 同 id+目标并发合并成一次写入', async () => {
264
+ let release
265
+ const gate = new Promise((r) => (release = r))
266
+ const fetchJson = stubFetch([async () => (await gate, { code: 200 })])
267
+ const s = svc({ fetchJson })
268
+ const p1 = s.setLiked(5, true)
269
+ const p2 = s.setLiked(5, true)
270
+ release()
271
+ const [a, b] = await Promise.all([p1, p2])
272
+ assert.equal(a.ok, true)
273
+ assert.equal(b.ok, true)
274
+ assert.equal(fetchJson.calls.length, 1)
275
+ })
276
+
277
+ test('apiBase 走 likeApiBase > dailyApiBase > 默认', async () => {
278
+ const f1 = stubFetch([{ code: 200, ids: [1] }])
279
+ await svc({ fetchJson: f1, getConfig: () => ({ likeApiBase: 'http://x/api/', dailyApiBase: 'http://y/api' }) }).isLiked(1)
280
+ assert.equal(f1.calls[0].url, 'http://x/api/song/like/check')
281
+ const f2 = stubFetch([{ code: 200, ids: [1] }])
282
+ await svc({ fetchJson: f2, getConfig: () => ({ dailyApiBase: 'http://y/api' }) }).isLiked(1)
283
+ assert.equal(f2.calls[0].url, 'http://y/api/song/like/check')
284
+ })
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // PlayerService.action('like')
288
+ // ---------------------------------------------------------------------------
289
+
290
+ function fakeLikePlayer({ like, songId = '123', cachedLiked = null } = {}) {
291
+ const backend = {
292
+ id: 'test',
293
+ platform: 'win32',
294
+ capabilities: { playback: true, sessionVolume: true, systemVolume: true, lyrics: true },
295
+ command: () => ({ shell: 'x', args: [] }),
296
+ }
297
+ const player = new PlayerService({ backend, getConfig: () => ({}), log: () => {}, like })
298
+ player.elog = { pollCount: 1, getState: () => ({ track: { songId } }) }
299
+ if (cachedLiked != null) like?.cache.set(String(songId), { liked: cachedLiked, at: Date.now() })
300
+ player.invalidate = () => {}
301
+ player.state = async () => ({ ok: true, now: { songId, liked: cachedLiked ?? false }, volume: null })
302
+ return player
303
+ }
304
+
305
+ test('player.action(like) 用 elog 的 songId,显式 like 目标态,回填 liked', async () => {
306
+ const setLiked = async (id, want) => {
307
+ assert.equal(id, '123')
308
+ assert.equal(want, true)
309
+ return { ok: true, liked: true }
310
+ }
311
+ const player = fakeLikePlayer({ like: { setLiked, cache: new Map() } })
312
+ const res = await player.action('like', { like: true })
313
+ assert.equal(res.ok, true)
314
+ assert.equal(res.liked, true)
315
+ assert.match(res.message, /我喜欢的音乐/)
316
+ })
317
+
318
+ test('player.action(like) 省略 like 时按缓存取反', async () => {
319
+ let got
320
+ const player = fakeLikePlayer({
321
+ like: { setLiked: async (id, want) => { got = want; return { ok: true, liked: want } }, cache: new Map([['123', { liked: true, at: Date.now() }]]) },
322
+ cachedLiked: true,
323
+ })
324
+ await player.action('like')
325
+ assert.equal(got, false)
326
+ })
327
+
328
+ test('player.action(like) 没注入 like 服务回 like-unavailable', async () => {
329
+ const player = fakeLikePlayer({ like: null })
330
+ const res = await player.action('like', { like: true })
331
+ assert.equal(res.ok, false)
332
+ assert.equal(res.error, 'like-unavailable')
333
+ })
334
+
335
+ test('player.action(like) 没有 songId 回 like-no-song', async () => {
336
+ const player = fakeLikePlayer({ like: { setLiked: async () => ({ ok: true, liked: true }), cache: new Map() }, songId: '' })
337
+ const res = await player.action('like', { like: true })
338
+ assert.equal(res.error, 'like-no-song')
339
+ })
340
+
341
+ test('player.action(like) 服务失败透传错误码', async () => {
342
+ const player = fakeLikePlayer({
343
+ like: { setLiked: async () => ({ ok: false, error: 'like-needs-login', message: '先登录' }), cache: new Map() },
344
+ })
345
+ const res = await player.action('like', { like: true })
346
+ assert.equal(res.ok, false)
347
+ assert.equal(res.error, 'like-needs-login')
348
+ assert.equal(res.message, '先登录')
349
+ })
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // 红心与客户端同步:state() 里的 likeSyncMs 节流状态机
353
+ // ---------------------------------------------------------------------------
354
+ //
355
+ // 客户端 elog 没有 like 事件,只能靠 state() 轮询服务器。下面这组盯住
356
+ // "切歌立即查 / 同曲每 likeSyncMs 强制重查 / 节流窗口读缓存 / 失败退避",
357
+ // 防止再退回"同一首歌只查一次、客户端点红心永远不同步"的老状态机。
358
+
359
+ function syncPlayer({ like, songId = '123', likeSyncMs = 8000 } = {}) {
360
+ const backend = {
361
+ id: 'test',
362
+ platform: 'win32',
363
+ capabilities: { playback: true },
364
+ command: () => ({ shell: 'x', args: [] }),
365
+ }
366
+ const player = new PlayerService({ backend, getConfig: () => ({ likeSyncMs }), log: () => {}, like })
367
+ player.elog = {
368
+ pollCount: 1,
369
+ noteSeek: () => {},
370
+ getState: () => ({
371
+ available: true, playing: true, positionMs: 0, durationMs: 1000, mode: '',
372
+ track: { songId, title: 't', artist: 'a', album: 'b' },
373
+ }),
374
+ }
375
+ player.request = async () => ({ ok: true, now: { songId, channel: 'native', peak: 0 }, volume: null })
376
+ player.invalidate = () => {}
377
+ return player
378
+ }
379
+
380
+ /** isLiked 桩:记录 force 参数,并像真 LikeService 一样回写 cache */
381
+ function likeStub(calls, { liked = true, ok = true, throwErr = false } = {}) {
382
+ const cache = new Map()
383
+ const isLiked = async (id, opts) => {
384
+ calls.push({ id, force: !!opts?.force })
385
+ if (throwErr) throw new Error('boom')
386
+ if (ok) cache.set(String(id), { liked, at: Date.now() })
387
+ return ok ? { ok: true, liked } : { ok: false, error: 'like-failed' }
388
+ }
389
+ return { cache, isLiked }
390
+ }
391
+
392
+ test('state 初次查 liked 用 force:true 强制回源,并回填 now.liked', async () => {
393
+ const calls = []
394
+ const like = likeStub(calls, { liked: true })
395
+ const p = syncPlayer({ like })
396
+ const s = await p.state({ fresh: true })
397
+ assert.equal(s.now.liked, true)
398
+ assert.equal(calls.length, 1)
399
+ assert.equal(calls[0].id, '123')
400
+ assert.equal(calls[0].force, true)
401
+ })
402
+
403
+ test('state 节流窗口内再查不重打服务器,从缓存读 liked', async () => {
404
+ const calls = []
405
+ const like = likeStub(calls, { liked: true })
406
+ const p = syncPlayer({ like })
407
+ await p.state({ fresh: true })
408
+ // 服务器值改成 false,若这一轮真去查了会变 false;只读缓存则应保持 true
409
+ like.cache.set('123', { liked: true, at: Date.now() })
410
+ const s2 = await p.state({ fresh: true })
411
+ assert.equal(calls.length, 1)
412
+ assert.equal(s2.now.liked, true)
413
+ })
414
+
415
+ test('state 到期后按 likeSyncMs 强制重查,覆盖缓存旧值(客户端点红心能同步)', async () => {
416
+ const calls = []
417
+ const like = likeStub(calls, { liked: true })
418
+ const p = syncPlayer({ like, likeSyncMs: 2000 })
419
+ await p.state({ fresh: true })
420
+ // 缓存伪造旧值 false,且把上次查询时间拉到 3s 前(>2000 窗口)
421
+ like.cache.set('123', { liked: false, at: Date.now() })
422
+ p.likedCheckedAt = Date.now() - 3000
423
+ const s = await p.state({ fresh: true })
424
+ assert.equal(calls.length, 2)
425
+ assert.equal(calls[1].force, true)
426
+ assert.equal(s.now.liked, true) // 服务器 true 覆盖缓存 false
427
+ })
428
+
429
+ test('state 切歌立即重查,不等 likeSyncMs 窗口', async () => {
430
+ const calls = []
431
+ const like = likeStub(calls, { liked: false })
432
+ const p = syncPlayer({ like, songId: '456' })
433
+ await p.state({ fresh: true })
434
+ // 换歌:likedForSong 还停在旧 id,likedCheckedAt 是刚刚 → 只靠 changed 触发
435
+ p.elog.getState = () => ({
436
+ available: true, playing: true, positionMs: 0, durationMs: 1000, mode: '',
437
+ track: { songId: '789', title: 't2', artist: 'a2', album: 'b2' },
438
+ })
439
+ p.request = async () => ({ ok: true, now: { songId: '789', channel: 'native', peak: 0 }, volume: null })
440
+ const s = await p.state({ fresh: true })
441
+ assert.equal(calls.length, 2)
442
+ assert.equal(calls[1].id, '789')
443
+ assert.equal(s.now.songId, '789')
444
+ assert.equal(s.now.liked, false)
445
+ })
446
+
447
+ test('state liked 查询失败后 15s 内退避,不每轮轮询都打失败接口', async () => {
448
+ const calls = []
449
+ const like = likeStub(calls, { ok: false })
450
+ const p = syncPlayer({ like })
451
+ await p.state({ fresh: true })
452
+ assert.equal(calls.length, 1)
453
+ // 窗口到期但失败未满 15s → retryOk=false,不查
454
+ p.likedCheckedAt = Date.now() - 9000
455
+ const s2 = await p.state({ fresh: true })
456
+ assert.equal(calls.length, 1)
457
+ assert.equal(s2.now.liked, null)
458
+ // 失败超过 15s → 允许重试
459
+ p.likedFailAt = Date.now() - 20000
460
+ await p.state({ fresh: true })
461
+ assert.equal(calls.length, 2)
462
+ })
463
+
464
+ test('state isLiked 抛异常也记 likedCheckedAt/likedFailAt,避免抖动', async () => {
465
+ const calls = []
466
+ const like = likeStub(calls, { throwErr: true })
467
+ const p = syncPlayer({ like })
468
+ const s = await p.state({ fresh: true })
469
+ assert.equal(s.now.liked, null)
470
+ assert.ok(p.likedCheckedAt > 0)
471
+ assert.ok(p.likedFailAt > 0)
472
+ assert.ok(p.likedFailAt >= p.likedCheckedAt)
473
+ })
474
+
475
+ test('toggleLike 成功后刷新 likedCheckedAt,下一轮 state 不立即重复回源', async () => {
476
+ const calls = []
477
+ const like = {
478
+ cache: new Map(),
479
+ isLiked: async (id, opts) => { calls.push({ id, force: !!opts?.force }); return { ok: true, liked: true } },
480
+ setLiked: async (id, want) => { like.cache.set(String(id), { liked: want, at: Date.now() }); return { ok: true, liked: want } },
481
+ }
482
+ const p = syncPlayer({ like })
483
+ p.likedCheckedAt = 0
484
+ const res = await p.action('like', { like: true })
485
+ assert.equal(res.ok, true)
486
+ assert.ok(p.likedCheckedAt > 0)
487
+ assert.equal(res.now.liked, true) // #toggleLike 内 state 回填读缓存
488
+ // native 幂等路径会用 isLiked 查一次服务端作代理;记下这次调用数
489
+ const callsAfterToggle = calls.length
490
+ // toggleLike 之后紧接着的 state 落在窗口内,不再额外回源
491
+ await p.state({ fresh: true })
492
+ assert.equal(calls.length, callsAfterToggle)
493
+ })
494
+
495
+ // ---------------------------------------------------------------------------
496
+ // DSH 点红心 → 同步客户端本地红心(native 全局 love 热键,不弹窗)
497
+ // ---------------------------------------------------------------------------
498
+ //
499
+ // 首选路径:force 查服务端作客户端状态代理,不一致就按热键让客户端自己 toggle
500
+ // 并写服务端,再 force 回填。native 不可用/失败一律回退 Web API(不弹窗)。
501
+
502
+ /** 带 setLike 请求桩的 player:requests 记录 helper 收到的 cmd */
503
+ function nativeLikePlayer({ liked = false, likeOk = true, setLikeReply = { ok: true, channel: 'native' }, setLikedCalls = null, requestThrow = false, playback = true } = {}) {
504
+ const requests = []
505
+ const cache = new Map()
506
+ const isLikedCalls = []
507
+ const like = {
508
+ cache,
509
+ isLiked: async (id, opts) => {
510
+ isLikedCalls.push({ id, force: !!opts?.force })
511
+ if (likeOk) cache.set(String(id), { liked, at: Date.now() })
512
+ return likeOk ? { ok: true, liked } : { ok: false, error: 'like-failed' }
513
+ },
514
+ setLiked: async (id, want) => {
515
+ if (setLikedCalls) setLikedCalls.push({ id, want })
516
+ cache.set(String(id), { liked: want, at: Date.now() })
517
+ return { ok: true, liked: want }
518
+ },
519
+ }
520
+ const backend = {
521
+ id: 'test', platform: 'win32',
522
+ capabilities: { playback, sessionVolume: true, systemVolume: true, lyrics: true },
523
+ command: () => ({ shell: 'x', args: [] }),
524
+ }
525
+ const player = new PlayerService({ backend, getConfig: () => ({}), log: () => {}, like })
526
+ player.elog = { pollCount: 1, getState: () => ({ track: { songId: '123' } }) }
527
+ player.request = async (cmd, payload, timeout) => {
528
+ requests.push({ cmd, payload, timeout })
529
+ if (requestThrow) throw new Error('helper gone')
530
+ return setLikeReply
531
+ }
532
+ player.invalidate = () => {}
533
+ player.state = async () => ({ ok: true, now: { songId: '123', liked: cache.get('123')?.liked ?? null }, volume: null })
534
+ player.likeSettleMs = 0 // 测试不真等 800ms
535
+ return { player, requests, isLikedCalls, setLikedCalls, cache }
536
+ }
537
+
538
+ test('native 同步:服务端 liked≠want 时按 setLike 热键并 force 回填(channel=native,不弹窗)', async () => {
539
+ // 服务端当前未喜欢(liked=false),目标 true → 按一次热键;客户端写服务端后
540
+ // isLiked 桩仍回 false(桩不变),回填应回退到 want=true(乐观)
541
+ const { player, requests } = nativeLikePlayer({ liked: false })
542
+ const res = await player.action('like', { like: true })
543
+ assert.equal(res.ok, true)
544
+ assert.equal(res.channel, 'native')
545
+ assert.equal(requests.length, 1)
546
+ assert.equal(requests[0].cmd, 'setLike')
547
+ })
548
+
549
+ test('native 同步:服务端 liked===want 时幂等,不按热键', async () => {
550
+ const { player, requests } = nativeLikePlayer({ liked: true })
551
+ const res = await player.action('like', { like: true })
552
+ assert.equal(res.ok, true)
553
+ assert.equal(res.channel, 'native')
554
+ assert.equal(res.skipped, 'already-set')
555
+ assert.equal(requests.length, 0)
556
+ })
557
+
558
+ test('native 失败(request 抛异常)回退 Web API setLiked', async () => {
559
+ const setLikedCalls = []
560
+ const { player } = nativeLikePlayer({ liked: false, requestThrow: true, setLikedCalls })
561
+ const res = await player.action('like', { like: true })
562
+ assert.equal(res.ok, true)
563
+ assert.equal(res.channel, 'web')
564
+ assert.equal(setLikedCalls.length, 1)
565
+ assert.equal(setLikedCalls[0].id, '123')
566
+ assert.equal(setLikedCalls[0].want, true)
567
+ })
568
+
569
+ test('native 无客户端会话(setLike 回 ok:false)回退 Web API setLiked', async () => {
570
+ const setLikedCalls = []
571
+ const { player } = nativeLikePlayer({ liked: false, setLikeReply: { ok: false, error: 'no-client' }, setLikedCalls })
572
+ const res = await player.action('like', { like: true })
573
+ assert.equal(res.ok, true)
574
+ assert.equal(res.channel, 'web')
575
+ assert.equal(setLikedCalls.length, 1)
576
+ })
577
+
578
+ test('native 不可用(backend.playback=false)直接走 Web API setLiked', async () => {
579
+ const setLikedCalls = []
580
+ const { player, requests } = nativeLikePlayer({ playback: false, setLikedCalls })
581
+ const res = await player.action('like', { like: true })
582
+ assert.equal(res.ok, true)
583
+ assert.equal(res.channel, 'web')
584
+ assert.equal(requests.length, 0)
585
+ assert.equal(setLikedCalls.length, 1)
586
+ })
587
+
588
+ // ---------------------------------------------------------------------------
589
+ // 大卡片副标题:elog 的来源 / 专辑透传到 now(前端据此显示)
590
+ // ---------------------------------------------------------------------------
591
+
592
+ /** 不注入 like(state 跳过 liked 查询),专测 #mergeElog 的 source/album 合成 */
593
+ function sourcePlayer(source) {
594
+ const backend = {
595
+ id: 'test',
596
+ platform: 'win32',
597
+ capabilities: { playback: true },
598
+ command: () => ({ shell: 'x', args: [] }),
599
+ }
600
+ const player = new PlayerService({ backend, getConfig: () => ({}), log: () => {} })
601
+ player.elog = {
602
+ pollCount: 1,
603
+ noteSeek: () => {},
604
+ getState: () => ({
605
+ available: true,
606
+ playing: true,
607
+ positionMs: 0,
608
+ durationMs: 1000,
609
+ mode: '',
610
+ track: { songId: '555', title: '歌', artist: '歌手', album: '专辑' },
611
+ source,
612
+ }),
613
+ }
614
+ player.request = async () => ({ ok: true, now: { songId: '555', channel: 'native', peak: 0 }, volume: null })
615
+ player.invalidate = () => {}
616
+ return player
617
+ }
618
+
619
+ test('state:elog 的 source 透传到 now.source(大卡片「来源:xxx」)', async () => {
620
+ const src = { scene: 'playlist', href: '/playlist/18334824318', text: '临时' }
621
+ const p = sourcePlayer(src)
622
+ const s = await p.state({ fresh: true })
623
+ assert.deepEqual(s.now.source, src)
624
+ assert.equal(s.now.album, '专辑')
625
+ })
626
+
627
+ test('state:elog 无 source 时 now.source 为 null(前端不显示来源)', async () => {
628
+ const p = sourcePlayer(null)
629
+ const s = await p.state({ fresh: true })
630
+ assert.equal(s.now.source, null)
631
+ })
632
+