@vicyangorg/dsh-music 0.3.0 → 0.5.0

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.
@@ -45,6 +45,16 @@ export function biasKeys(keys, prefer) {
45
45
  ]
46
46
  }
47
47
 
48
+ /** 新歌窗口:近 180 天新发行才算「新歌」(八期①纠偏;Chief 允许自定,取半年)。 */
49
+ export const NEW_RELEASE_DAYS = 180
50
+
51
+ /** 新歌理由:发行年必须来自真实发行日期(不是入库时间)。 */
52
+ export function newReleaseReason(artist, releaseDate, album, releaseType = 'Album') {
53
+ const year = String(releaseDate ?? '').slice(0, 4)
54
+ const rel = releaseType === 'Single' ? '单曲' : releaseType === 'EP' ? 'EP' : album ? `专辑《${album}》` : '单曲'
55
+ return year ? `新歌推荐:${artist} ${year} 年发行${rel}` : `新歌推荐:${artist} 近期发行${rel}`
56
+ }
57
+
48
58
  export function createDiscover({ storage, logger } = {}) {
49
59
  const warn = (msg) => logger?.warn?.(msg)
50
60
  const dir = join(storage.dataDir, 'cache', 'reco')
@@ -324,6 +334,44 @@ export function createDiscover({ storage, logger } = {}) {
324
334
  return groups
325
335
  }
326
336
 
337
+ /** 近期发行曲目(已实测路径:release-group → release → recording,recording 不支持直接按 rg browse)。
338
+ * sinceDays 内的 Album/Single/EP,取最近 maxReleases 张、每张 perRelease 首。 */
339
+ /** release-group → releases → recordings(各层缓存 7 天;recording 不支持直接按 rg browse)。 */
340
+ async function recordingsFromReleaseGroup(g, perRelease = 3) {
341
+ const relKey = `releases-${g.rgid}.json`
342
+ let releases = (await cacheRead(relKey, RECORDINGS_TTL_MS))?.releases
343
+ if (!releases) {
344
+ try {
345
+ const data = await mbJson(mbUrl('release', { 'release-group': g.rgid, limit: 5 }), { logger })
346
+ releases = (data?.releases ?? []).map((r) => ({ rid: r.id, title: r.title, date: r.date }))
347
+ await cacheWrite(relKey, { releases })
348
+ } catch (err) {
349
+ warn?.(`dsh-music: browse releases 失败 ${g.rgid}: ${err.message}`)
350
+ return []
351
+ }
352
+ }
353
+ if (!releases?.[0]) return []
354
+ const recKey = `recordings-release-${releases[0].rid}.json`
355
+ let recs = (await cacheRead(recKey, RECORDINGS_TTL_MS))?.recordings
356
+ if (!recs) {
357
+ try {
358
+ const data = await mbJson(mbUrl('recording', { release: releases[0].rid, limit: 10, inc: 'artist-credits' }), { logger })
359
+ recs = (data?.recordings ?? [])
360
+ .filter((r) => !r.video && r.title && r['artist-credit']?.[0]?.name)
361
+ .map((r) => ({
362
+ artist: r['artist-credit'][0].name,
363
+ title: r.title,
364
+ durationMs: Number.isFinite(r.length) ? r.length : undefined,
365
+ }))
366
+ await cacheWrite(recKey, { recordings: recs })
367
+ } catch (err) {
368
+ warn?.(`dsh-music: browse release recordings 失败 ${releases[0].rid}: ${err.message}`)
369
+ return []
370
+ }
371
+ }
372
+ return (recs ?? []).slice(0, perRelease).map((r) => ({ ...r, album: g.title, releaseDate: g.date, releaseType: g.type }))
373
+ }
374
+
327
375
  /** 近期发行曲目(已实测路径:release-group → release → recording,recording 不支持直接按 rg browse)。
328
376
  * sinceDays 内的 Album/Single/EP,取最近 maxReleases 张、每张 perRelease 首。 */
329
377
  async function recentReleaseRecordings(mbid, { sinceDays = 730, maxReleases = 2, perRelease = 3 } = {}) {
@@ -332,47 +380,38 @@ export function createDiscover({ storage, logger } = {}) {
332
380
  .filter((g) => g.date >= cutoff && ['Album', 'Single', 'EP'].includes(g.type))
333
381
  .slice(0, maxReleases)
334
382
  const out = []
335
- for (const g of groups) {
336
- // release-group → releases(缓存)
337
- const relKey = `releases-${g.rgid}.json`
338
- let releases = (await cacheRead(relKey, RECORDINGS_TTL_MS))?.releases
339
- if (!releases) {
340
- try {
341
- const data = await mbJson(mbUrl('release', { 'release-group': g.rgid, limit: 5 }), { logger })
342
- releases = (data?.releases ?? []).map((r) => ({ rid: r.id, title: r.title, date: r.date }))
343
- await cacheWrite(relKey, { releases })
344
- } catch (err) {
345
- warn?.(`dsh-music: browse releases 失败 ${g.rgid}: ${err.message}`)
346
- continue
347
- }
348
- }
349
- if (!releases?.[0]) continue
350
- // release → recordings(缓存)
351
- const recKey = `recordings-release-${releases[0].rid}.json`
352
- let recs = (await cacheRead(recKey, RECORDINGS_TTL_MS))?.recordings
353
- if (!recs) {
354
- try {
355
- const data = await mbJson(mbUrl('recording', { release: releases[0].rid, limit: 10, inc: 'artist-credits' }), { logger })
356
- recs = (data?.recordings ?? [])
357
- .filter((r) => !r.video && r.title && r['artist-credit']?.[0]?.name)
358
- .map((r) => ({
359
- artist: r['artist-credit'][0].name,
360
- title: r.title,
361
- durationMs: Number.isFinite(r.length) ? r.length : undefined,
362
- }))
363
- await cacheWrite(recKey, { recordings: recs })
364
- } catch (err) {
365
- warn?.(`dsh-music: browse release recordings 失败 ${releases[0].rid}: ${err.message}`)
366
- continue
367
- }
368
- }
369
- for (const r of (recs ?? []).slice(0, perRelease)) {
370
- out.push({ ...r, album: g.title, releaseDate: g.date })
371
- }
372
- }
383
+ for (const g of groups) out.push(...await recordingsFromReleaseGroup(g, perRelease))
373
384
  return out
374
385
  }
375
386
 
387
+ /** 按流派标签检索「近 N 天首发」的专辑/单曲/EP(八期①拓宽新歌来源,不限于高频歌手)。
388
+ * MB release-group search 支持 tag + firstreleasedate;结果按首发日期降序、剔除 Live/精选。 */
389
+ async function searchRecentReleaseGroups(tag, { sinceDays = NEW_RELEASE_DAYS, limit = 6 } = {}) {
390
+ const cutoff = new Date(Date.now() - sinceDays * 24 * 3600 * 1000).toISOString().slice(0, 10)
391
+ const key = `rgsearch-${createHash('sha1').update(`${norm(tag)}|${cutoff}`).digest('hex').slice(0, 16)}.json`
392
+ const cached = await cacheRead(key, RECORDINGS_TTL_MS)
393
+ if (cached) return cached.groups ?? []
394
+ let groups = []
395
+ try {
396
+ const query = `tag:"${tag}" AND firstreleasedate:[${cutoff} TO *]`
397
+ const data = await mbJson(mbUrl('release-group', { query, limit: 25 }), { logger })
398
+ const skipSecondary = new Set(['Live', 'Compilation', 'Remix', 'Interview', 'Demo'])
399
+ const today = new Date().toISOString().slice(0, 10)
400
+ groups = (data?.['release-groups'] ?? [])
401
+ .filter((g) => g.id && g['first-release-date'] && g['first-release-date'] >= cutoff && g['first-release-date'] <= today
402
+ && ['Album', 'Single', 'EP'].includes(g['primary-type'])
403
+ && !(g['secondary-types'] ?? []).some((t) => skipSecondary.has(t)))
404
+ .sort((a, b) => String(b['first-release-date']).localeCompare(String(a['first-release-date'])))
405
+ .slice(0, limit)
406
+ .map((g) => ({ rgid: g.id, title: g.title, date: g['first-release-date'], type: g['primary-type'] }))
407
+ await cacheWrite(key, { groups })
408
+ } catch (err) {
409
+ warn?.(`dsh-music: 近期发行检索失败 ${tag}: ${err.message}`)
410
+ return [] // 失败不缓存
411
+ }
412
+ return groups
413
+ }
414
+
376
415
  /** 歌手栏目候选:高频歌手 → MB artist-rels 相似歌手 → 其作品(不含种子本人)。
377
416
  * 游标轮换相似歌手取样,批间不重样。返回 {candidates, cursor}。 */
378
417
  async function buildArtistCandidates({ seedArtists, libraryKeys, recentKeys, extraKeys, cursor = 0, limit = 6 }) {
@@ -514,54 +553,98 @@ export function createDiscover({ storage, logger } = {}) {
514
553
 
515
554
  /** 新歌栏目候选:曲库近 30 天新增(本地,优先)+ 高频歌手 MB 近两年新发行(补充)。
516
555
  * 全部候选仍须过 verify.js 核实;本地曲核实失败则不输出(守「先核实再输出」红线)。 */
517
- async function buildNewCandidates({ tracks, getRecord, seedArtists, libraryKeys, recentKeys, extraKeys, limit = 6 }) {
556
+ /** 新歌候选(八期①):新歌 = 真正的新发行(近 NEW_RELEASE_DAYS 天),不再把
557
+ * 「曲库刚入库」当新歌(刚入库是用户已有的歌,不属于新歌发现)。
558
+ * 来源顺序:高频歌手 → 相似歌手(artist-rels)→ 口味/画像流派代表歌手;
559
+ * 每首仍必须经 verify.js 核实;去重曲库/近期播放/已推荐;跳过不喜欢过的曲目与歌手
560
+ * (只读 dislikes 标记,不把口味事件当播放画像)。 */
561
+ async function buildNewCandidates({
562
+ seedArtists = [], libraryKeys = new Set(), recentKeys = new Set(), extraKeys = new Set(),
563
+ tasteGenres = [], dislikedKeys = new Set(), dislikedArtists = new Set(), limit = 20,
564
+ }) {
518
565
  const seen = new Set([...recentKeys, ...(extraKeys ?? [])])
566
+ const artistSeen = new Set()
519
567
  const baseKey = (artist, title) => normKey(artist, String(title).replace(/[((].*?[))]/g, ''))
568
+ const dislikedArtist = (name) => dislikedArtists.has(String(name ?? '').trim().toLowerCase())
520
569
  const out = []
570
+ const albumCount = new Map() // 同一专辑最多进 2 首,防一张专辑刷屏
521
571
  const push = (c) => {
522
572
  const key = baseKey(c.artist, c.title)
523
- if (!key || seen.has(key)) return
573
+ if (!key || seen.has(key) || libraryKeys.has(key)) return
574
+ if (dislikedKeys.has(normKey(c.artist, c.title)) || dislikedArtist(c.artist)) return
575
+ const ak = c.album ? baseKey(c.artist, c.album) : null
576
+ if (ak && (albumCount.get(ak) ?? 0) >= 2) return
524
577
  seen.add(key)
578
+ if (ak) albumCount.set(ak, (albumCount.get(ak) ?? 0) + 1)
525
579
  out.push(c)
526
580
  }
527
- // 1) 曲库近期新增(按文件 mtime 降序,30 天内)
528
- const cutoff = Date.now() - 30 * 24 * 3600 * 1000
529
- const local = []
530
- for (const t of tracks ?? []) {
531
- const rec = getRecord?.(t.id)
532
- const mtime = rec?.meta?.mtimeMs
533
- if (!Number.isFinite(mtime) || mtime < cutoff) continue
534
- local.push({ t, mtime })
535
- }
536
- local.sort((a, b) => b.mtime - a.mtime)
537
- for (const { t, mtime } of local.slice(0, limit + 4)) {
538
- const rec = getRecord?.(t.id)
539
- const date = new Date(mtime).toISOString().slice(0, 10)
540
- push({
541
- category: 'new', artist: t.artist, title: t.title,
542
- album: t.album ?? undefined,
543
- durationMs: Number.isFinite(rec?.meta?.duration) ? Math.round(rec.meta.duration * 1000) : undefined,
544
- local: true, trackId: t.id,
545
- coverUrl: t.coverUrl || undefined,
546
- reason: `新歌推荐:${date} 新加入曲库`,
547
- })
581
+ const takeArtist = (mbid, name) => {
582
+ if (!mbid || artistSeen.has(mbid) || dislikedArtist(name)) return false
583
+ artistSeen.add(mbid)
584
+ return true
548
585
  }
549
- // 2) MB 近期发行(高频歌手,best-effort 补充)
550
- for (const name of seedArtists.slice(0, 4)) {
551
- if (out.length >= limit + 10) break
552
- const a = await findArtist(name)
553
- if (!a) continue
554
- const recs = await recentReleaseRecordings(a.mbid, { sinceDays: 1095, maxReleases: 4, perRelease: 6 })
586
+ const enough = () => out.length >= limit + 4
587
+ const take = async (mbid, { maxReleases = 1, perRelease = 6 } = {}) => {
588
+ const recs = await recentReleaseRecordings(mbid, { sinceDays: NEW_RELEASE_DAYS, maxReleases, perRelease })
589
+ const today = new Date().toISOString().slice(0, 10)
590
+ const cutoff = new Date(Date.now() - NEW_RELEASE_DAYS * 24 * 3600 * 1000).toISOString().slice(0, 10)
555
591
  for (const r of recs) {
556
- if (out.length >= limit + 8) break
557
- if (libraryKeys.has(baseKey(r.artist, r.title))) continue
592
+ if (!r?.releaseDate || r.releaseDate < cutoff || r.releaseDate > today) continue
558
593
  push({
559
- category: 'new', artist: r.artist, title: r.title, album: r.album, durationMs: r.durationMs,
560
- reason: `新歌推荐:${r.artist} ${String(r.releaseDate).slice(0, 4)} 年新发行《${r.album}》`,
594
+ category: 'new', artist: r.artist, title: r.title, album: r.album,
595
+ durationMs: r.durationMs, releaseDate: r.releaseDate,
596
+ reason: newReleaseReason(r.artist, r.releaseDate, r.album, r.releaseType),
561
597
  })
562
598
  }
563
599
  }
564
- return out
600
+ // 1) 高频歌手(画像种子):每位取最近 2 张发行
601
+ for (const name of seedArtists.slice(0, 3)) {
602
+ if (enough()) break
603
+ const a = await findArtist(name)
604
+ if (!a || !takeArtist(a.mbid, a.name)) continue
605
+ await take(a.mbid, { maxReleases: 2 })
606
+ }
607
+ // 2) 相似歌手(artist-rels):最多 2 位种子 × 2 位关系歌手
608
+ if (!enough()) {
609
+ for (const name of seedArtists.slice(0, 2)) {
610
+ if (enough()) break
611
+ const a = await findArtist(name)
612
+ if (!a) continue
613
+ const rels = await relatedArtists(a.mbid)
614
+ let n = 0
615
+ for (const rel of rels) {
616
+ if (n >= 2 || enough()) break
617
+ if (!takeArtist(rel.mbid, rel.name)) continue
618
+ await take(rel.mbid, { maxReleases: 1 })
619
+ n++
620
+ }
621
+ }
622
+ }
623
+ // 3) 口味/画像流派:按 tag + 首发日期直查近期发行(不限高频歌手),每流派最多取 3 张
624
+ if (!enough()) {
625
+ for (const tag of tasteGenres.slice(0, 3)) {
626
+ if (enough()) break
627
+ const groups = await searchRecentReleaseGroups(tag, { limit: 6 })
628
+ let n = 0
629
+ for (const g of groups) {
630
+ if (n >= 3 || enough()) break
631
+ const today = new Date().toISOString().slice(0, 10)
632
+ if (!g.date || g.date > today) continue
633
+ const recs = await recordingsFromReleaseGroup(g, 6)
634
+ for (const r of recs) {
635
+ push({
636
+ category: 'new', artist: r.artist, title: r.title, album: r.album ?? g.title,
637
+ durationMs: r.durationMs, releaseDate: r.releaseDate ?? g.date,
638
+ reason: newReleaseReason(r.artist, r.releaseDate ?? g.date, r.album ?? g.title, r.releaseType ?? g.type),
639
+ })
640
+ }
641
+ n++
642
+ }
643
+ }
644
+ }
645
+ // 真实发行日期降序(最新在前)
646
+ out.sort((a, b) => String(b.releaseDate ?? '').localeCompare(String(a.releaseDate ?? '')))
647
+ return out.slice(0, limit + 8)
565
648
  }
566
649
 
567
650
  return { findArtist, artistInfo, searchArtistsByTag, buildArtistList, browseRecordings, relatedArtists, searchByTag, searchRecordings, buildSimilarCandidates, buildExploreCandidates, browseReleaseGroups, recentReleaseRecordings, buildArtistCandidates, buildNewCandidates }
@@ -10,8 +10,8 @@
10
10
  * const reco = createReco({ history, library, storage, config, logger })
11
11
  * ctx.effect 内:...registerRecoRoutes(ctx.webServer, { reco, logger });清理 reco.dispose()
12
12
  * 打包:package.json files 需含 host/reco 下全部 js(host 双星 glob 已覆盖)。 */
13
- import { join } from 'node:path'
14
- import { readFile, writeFile, rename } from 'node:fs/promises'
13
+ import { join, dirname } from 'node:path'
14
+ import { readFile, writeFile, rename, mkdir } from 'node:fs/promises'
15
15
  import { createVerifier } from './verify.js'
16
16
  import { createDiscover } from './discover.js'
17
17
  import { detectLanguage } from './diversity.js'
@@ -46,11 +46,30 @@ export function createReco({ history, library, storage, config = {}, logger, ver
46
46
  }
47
47
 
48
48
  async function writeJson(file, value) {
49
+ await mkdir(dirname(file), { recursive: true })
49
50
  const tmp = `${file}.tmp-${process.pid}`
50
51
  await writeFile(tmp, JSON.stringify(value), 'utf8')
51
52
  await rename(tmp, file)
52
53
  }
53
54
 
55
+ /** 不喜欢标记(八期④):只读 likes.json v2 的 dislikes,不进播放画像(口味事件不参与历史统计)。
56
+ * 返回归一后的「歌手::歌名」集合 + 小写歌手集合(歌手级软降权用)。文件不存在视为零。 */
57
+ async function readDislikes() {
58
+ const saved = await readJson(join(storage.dataDir, 'likes.json'), null)
59
+ const dislikes = saved && typeof saved.dislikes === 'object' && saved.dislikes !== null ? saved.dislikes : {}
60
+ const keys = new Set()
61
+ const artists = new Set()
62
+ for (const d of Object.values(dislikes)) {
63
+ if (!d || typeof d !== 'object') continue
64
+ const artist = typeof d.artist === 'string' ? d.artist : ''
65
+ const title = typeof d.title === 'string' ? d.title : ''
66
+ if (!artist || !title) continue
67
+ keys.add(normKey(artist, title))
68
+ artists.add(artist.trim().toLowerCase())
69
+ }
70
+ return { keys, artists }
71
+ }
72
+
54
73
  /** 生成一批推荐(10 首 = 7 相近 + 3 探索,逐首已核实)。纯算法 + MusicBrainz,无 LLM。
55
74
  * 可选 options.taste(v7 批2:客户端首启偏好 {genres[],languages[]})仅软偏置探索轴,不传时行为不变。 */
56
75
  async function generate(options = {}) {
@@ -285,8 +304,20 @@ export function createReco({ history, library, storage, config = {}, logger, ver
285
304
  let profile = cached?.data ?? null
286
305
  let message = null
287
306
  if (!profile) {
288
- profile = await liveWikiProfile(a.name)
289
- if (!profile) message = '暂无该歌手资料'
307
+ const live = await liveWikiProfile(a.name)
308
+ if (live) {
309
+ // 九期点4:live 维基兜底成功即持久化(与 metadata/artist.js 同一缓存格式/路径,两条路径共享,
310
+ // TTL 内重开零网络拉取);写失败只告警,不影响本次返回。
311
+ const data = { name: a.name, ...live }
312
+ try {
313
+ await writeJson(cacheFile, { version: 1, data, fetchedAt: Date.now() })
314
+ } catch (err) {
315
+ warn?.(`dsh-music: 回写歌手缓存失败 ${a.name}: ${err.message}`)
316
+ }
317
+ profile = data
318
+ } else {
319
+ message = '暂无该歌手资料'
320
+ }
290
321
  }
291
322
  if (typeof library.ensureScanned === 'function') await library.ensureScanned()
292
323
  const tracks = library.snapshot()?.tracks ?? []
@@ -301,12 +332,14 @@ export function createReco({ history, library, storage, config = {}, logger, ver
301
332
  const recs = await discover.browseRecordings(a.mbid, a.name)
302
333
  const songs = []
303
334
  const seen = new Set()
335
+ const { keys: dislikedKeys } = await readDislikes()
304
336
  // 去括号版本后缀去重(Live/Remix 版不重复占位)
305
337
  const baseKey = (artist, title) => normKey(artist, String(title).replace(/[((].*?[))]/g, ''))
306
338
  for (const r of recs) {
307
339
  if (songs.length >= 20) break
308
340
  const key = baseKey(r.artist, r.title)
309
341
  if (!key || seen.has(key)) continue
342
+ if (dislikedKeys.has(normKey(r.artist, r.title))) continue
310
343
  seen.add(key)
311
344
  const v = await verifier.verify({ artist: r.artist, title: r.title, durationMs: r.durationMs })
312
345
  if (!v) continue
@@ -339,6 +372,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
339
372
  }
340
373
  const tracks = snap?.tracks ?? []
341
374
  const { seedArtists, topArtistSet, profileValues, profile, libraryKeys, recentKeys } = await buildProfile(events, tracks)
375
+ const { keys: dislikedKeys, artists: dislikedArtists } = await readDislikes()
342
376
 
343
377
  // ---- 探索轴轮换(quota.js,批间轮转 + 固定意外之喜位)----
344
378
  const state = await readJson(stateFile, {})
@@ -352,9 +386,15 @@ export function createReco({ history, library, storage, config = {}, logger, ver
352
386
  const exploreResult = await discover.buildExploreCandidates({
353
387
  slots: plan.slots, profileValues, cursors: state.cursors ?? {}, taste,
354
388
  })
355
- const candidates = [
389
+ const deduped = [
356
390
  ...similar,
357
391
  ...exploreResult.candidates.filter((c) => !recentRecommended.has(normKey(c.artist, c.title))),
392
+ ].filter((c) => !dislikedKeys.has(normKey(c.artist, c.title)))
393
+ // ④ 避开不喜欢:标记过的歌直接排除;同歌手的其余曲目软降权(排到最后,仅在候选不足时补位)
394
+ const isDislikedArtist = (c) => dislikedArtists.has(String(c.artist ?? '').trim().toLowerCase())
395
+ const candidates = [
396
+ ...deduped.filter((c) => !isDislikedArtist(c)),
397
+ ...deduped.filter((c) => isDislikedArtist(c)),
358
398
  ]
359
399
  const needSimilar = bootstrap ? 0 : SIMILAR_SLOTS
360
400
  if (candidates.length < needSimilar + EXPLORE_SLOTS) {
@@ -475,7 +515,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
475
515
  if (typeof library.ensureScanned === 'function') await library.ensureScanned()
476
516
  const snap = library.snapshot()
477
517
  const tracks = snap?.tracks ?? []
478
- const { seedArtists, libraryKeys, recentKeys } = await buildProfile(events, tracks)
518
+ const { seedArtists, libraryKeys, recentKeys, profile } = await buildProfile(events, tracks)
479
519
 
480
520
  // today:同一自然日「且数量达标(>= 14+6)」才复用最近一批;否则生成新批次(推进探索轴轮换)。
481
521
  // 旧版本(二期 10 首/批)的当日批次不足 20,必须重生成,否则活体会显示 10 首。
@@ -534,11 +574,14 @@ export function createReco({ history, library, storage, config = {}, logger, ver
534
574
  const imgMap = await images.artistImages(artistResult.artists.map((a) => a.name))
535
575
  const artist = artistResult.artists.map((a) => ({ ...a, imageUrl: imgMap.get(a.name)?.thumbnail ?? null }))
536
576
 
537
- // new:曲库近 30 天新增(本地)+ MB 近两年新发行(补充)
577
+ // new:真正的新发行(近 180 天,八期①)——高频歌手/相似歌手/口味流派来源;本地刚入库不算新歌
578
+ const disliked = await readDislikes()
579
+ const tasteGenres = (taste?.genres?.length ? taste.genres : profile.genres).slice(0, 4)
538
580
  const usedForNew = new Set(usedKeys)
539
- const newCands = await discover.buildNewCandidates({
540
- tracks, getRecord: (id) => library.getRecord(id), seedArtists, libraryKeys, recentKeys, extraKeys: usedForNew, limit: 20,
541
- })
581
+ const newCands = (await discover.buildNewCandidates({
582
+ tracks, getRecord: (id) => library.getRecord(id), seedArtists, libraryKeys, recentKeys, extraKeys: usedForNew,
583
+ tasteGenres, dislikedKeys: disliked.keys, dislikedArtists: disliked.artists, limit: 20,
584
+ })).filter((c) => !disliked.keys.has(normKey(c.artist, c.title)))
542
585
  const fresh = await verifyToItems(newCands, { limit: 20, category: 'new', usedKeys: usedForNew })
543
586
 
544
587
  // 持久化歌手轮换游标(merge 现有 state,不覆盖其余字段)
@@ -55,6 +55,34 @@ export const GENRE_POOLS = {
55
55
  ambient: [
56
56
  { artist: 'Brian Eno', title: 'An Ending (Ascent)' },
57
57
  { artist: 'Sigur Rós', title: 'Hoppípolla' },
58
+ { artist: 'Moby', title: 'Porcelain' },
59
+ ],
60
+ // 八期②:对齐欢迎页 genreOptions 15 个流派(织音 client 已扩到 15)。
61
+ // 'hip hop' 保留空格键名,与 style.js / MB tag 口径一致(客户端传 'hip hop')。
62
+ rock: [
63
+ { artist: 'The Rolling Stones', title: 'Paint It Black' },
64
+ { artist: 'Led Zeppelin', title: 'Stairway to Heaven' },
65
+ { artist: 'Nirvana', title: 'Smells Like Teen Spirit' },
66
+ ],
67
+ pop: [
68
+ { artist: 'Michael Jackson', title: 'Billie Jean' },
69
+ { artist: 'Madonna', title: 'Like a Prayer' },
70
+ { artist: 'Taylor Swift', title: 'Shake It Off' },
71
+ ],
72
+ 'hip hop': [
73
+ { artist: 'Kendrick Lamar', title: 'HUMBLE.' },
74
+ { artist: 'Wu-Tang Clan', title: 'C.R.E.A.M.' },
75
+ { artist: 'Lauryn Hill', title: 'Doo Wop (That Thing)' },
76
+ ],
77
+ punk: [
78
+ { artist: 'The Clash', title: 'London Calling' },
79
+ { artist: 'Ramones', title: 'Blitzkrieg Bop' },
80
+ { artist: 'Sex Pistols', title: 'Anarchy in the U.K.' },
81
+ ],
82
+ country: [
83
+ { artist: 'Johnny Cash', title: 'Ring of Fire' },
84
+ { artist: 'Dolly Parton', title: 'Jolene' },
85
+ { artist: 'Willie Nelson', title: 'On the Road Again' },
58
86
  ],
59
87
  }
60
88
 
@@ -7,6 +7,7 @@ import { createHash } from 'node:crypto'
7
7
  import { mbJson, mbUrl } from './mb.js'
8
8
 
9
9
  const CACHE_TTL_MS = 30 * 24 * 3600 * 1000
10
+ const NEG_TTL_MS = 3 * 24 * 3600 * 1000 // 未命中负缓存 3 天(与 images.js 无图负缓存一致)
10
11
 
11
12
  function norm(s) {
12
13
  return String(s ?? '').toLowerCase().replace(/[\s'"’·・\-—–,,.。!!??::;;()()\[\]【】]/g, '')
@@ -28,6 +29,26 @@ export function createVerifier({ storage, logger } = {}) {
28
29
  return null
29
30
  }
30
31
 
32
+ /** 未命中负缓存:只挡重查,绝不构成「核实通过」——下载前仍以 verify 返回记录为准。 */
33
+ async function readNegative(key) {
34
+ try {
35
+ const saved = JSON.parse(await readFile(join(dir, `${key}.json`), 'utf8'))
36
+ if (saved?.miss === true && Number.isFinite(saved.missedAt) && Date.now() - saved.missedAt < NEG_TTL_MS) return true
37
+ } catch { /* 无缓存 */ }
38
+ return false
39
+ }
40
+
41
+ async function writeNegative(key, artist, title) {
42
+ try {
43
+ await mkdir(dir, { recursive: true })
44
+ const tmp = join(dir, `${key}.tmp-${process.pid}`)
45
+ await writeFile(tmp, JSON.stringify({ miss: true, missedAt: Date.now(), artist, title }), 'utf8')
46
+ await rename(tmp, join(dir, `${key}.json`))
47
+ } catch (err) {
48
+ warn?.(`dsh-music: 写核实负缓存失败: ${err.message}`)
49
+ }
50
+ }
51
+
31
52
  async function writeCache(key, record) {
32
53
  try {
33
54
  await mkdir(dir, { recursive: true })
@@ -62,6 +83,7 @@ export function createVerifier({ storage, logger } = {}) {
62
83
  const key = cacheKey(artist, title)
63
84
  const cached = await readCache(key)
64
85
  if (cached) return cached
86
+ if (await readNegative(key)) return null // 3 天内已确认未命中,不重复打 MusicBrainz
65
87
 
66
88
  const query = `artist:"${artist}" AND recording:"${title}"`
67
89
  const url = mbUrl('recording', { query, limit: 8 })
@@ -76,7 +98,10 @@ export function createVerifier({ storage, logger } = {}) {
76
98
  const target = Number(durationMs) > 0 ? Number(durationMs) : null
77
99
  const recordings = Array.isArray(data?.recordings) ? data.recordings : []
78
100
  const hits = recordings.filter((r) => artistMatches(r['artist-credit'] ?? [], artist) && titleMatches(r.title, title))
79
- if (hits.length === 0) return null
101
+ if (hits.length === 0) {
102
+ await writeNegative(key, artist, title) // 网络失败不落负缓存(仅确定性未命中)
103
+ return null
104
+ }
80
105
  let best = hits[0]
81
106
  if (target !== null) {
82
107
  const withDur = hits.filter((r) => Number.isFinite(r.length))
package/icon.png ADDED
Binary file
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.3.0",
6
+ "version": "0.5.0",
7
7
  "private": false,
8
8
  "license": "MIT",
9
9
  "author": "vicyangworld",
@@ -35,7 +35,7 @@
35
35
  ".": "./index.js",
36
36
  "./client": "./client/index.js",
37
37
  "./locale/*.json": "./locale/*.json",
38
- "./icon": "./icon.svg"
38
+ "./icon": "./icon.png"
39
39
  },
40
40
  "files": [
41
41
  "index.js",
@@ -43,7 +43,7 @@
43
43
  "client/index.js",
44
44
  "cordis.patch.yml",
45
45
  "locale/*.json",
46
- "icon.svg",
46
+ "icon.png",
47
47
  "docs/DETAIL.md",
48
48
  "docs/assets/*"
49
49
  ],
package/icon.svg DELETED
@@ -1,16 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
2
- <defs>
3
- <linearGradient id="dshm-bg" x1="0" y1="0" x2="1" y2="1">
4
- <stop offset="0" stop-color="#4f46e5"/>
5
- <stop offset="1" stop-color="#8b5cf6"/>
6
- </linearGradient>
7
- </defs>
8
- <rect x="8" y="8" width="240" height="240" rx="56" fill="url(#dshm-bg)"/>
9
- <g fill="#ffffff">
10
- <polygon points="98,78 196,60 196,76 98,94"/>
11
- <rect x="98" y="86" width="10" height="88" rx="3"/>
12
- <rect x="186" y="68" width="10" height="88" rx="3"/>
13
- <ellipse cx="88" cy="174" rx="21" ry="15" transform="rotate(-14 88 174)"/>
14
- <ellipse cx="176" cy="156" rx="21" ry="15" transform="rotate(-14 176 156)"/>
15
- </g>
16
- </svg>