@vicyangorg/dsh-music 0.4.0 → 0.6.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.
Binary file
Binary file
Binary file
@@ -3,6 +3,8 @@
3
3
  import { slugify } from './cache.js'
4
4
 
5
5
  const UA = 'dsh-music/0.1 (local music plugin; artist content)'
6
+ /** 九期点4:简介/资料缓存 TTL 30 天(Chief 建议 7–30 天取上限),过期后下次打开刷新。 */
7
+ const PROFILE_TTL_MS = 30 * 24 * 3600 * 1000
6
8
 
7
9
  function today() {
8
10
  return new Date().toISOString().slice(0, 10)
@@ -50,7 +52,8 @@ export function createArtistContent({ cache, logger }) {
50
52
  async get(name) {
51
53
  const slug = slugify(name)
52
54
  const hit = await cache.readJson(cache.artistFile(slug))
53
- if (hit && hit.version === 1 && hit.data) {
55
+ const fresh = hit && hit.version === 1 && hit.data && Date.now() - (hit.fetchedAt ?? 0) < PROFILE_TTL_MS
56
+ if (fresh) {
54
57
  const d = hit.data
55
58
  return {
56
59
  name: d.name ?? name,
@@ -66,13 +69,30 @@ export function createArtistContent({ cache, logger }) {
66
69
  }
67
70
  const intro = await wikiIntro(name)
68
71
  if (intro) {
72
+ // 九期点4:live 兜底成功即持久化(TTL 内重开零网络拉取);写失败只警告不影响返回。
73
+ // 过期刷新时合并保留原有调研字段(news/trivia/similar 不被空数组覆盖)。
74
+ const old = hit?.data ?? {}
75
+ const keep = (cur, prev) => (Array.isArray(cur) && cur.length > 0 ? cur : Array.isArray(prev) ? prev : [])
76
+ const data = {
77
+ name,
78
+ intro,
79
+ news: keep([], old.news),
80
+ trivia: keep([], old.trivia),
81
+ similarArtists: keep([], old.similarArtists),
82
+ similarSongs: keep([], old.similarSongs),
83
+ }
84
+ try {
85
+ await cache.writeJson(cache.artistFile(slug), { version: 1, data, fetchedAt: Date.now() })
86
+ } catch (err) {
87
+ warn(`dsh-music: 回写歌手缓存失败 ${name}: ${err.message}`)
88
+ }
69
89
  return {
70
90
  name,
71
91
  intro,
72
- news: [],
73
- trivia: [],
74
- similarArtists: [],
75
- similarSongs: [],
92
+ news: data.news,
93
+ trivia: data.trivia,
94
+ similarArtists: data.similarArtists,
95
+ similarSongs: data.similarSongs,
76
96
  cached: false,
77
97
  fetchedAt: Date.now(),
78
98
  message: '动态/逸闻/相似内容由调研补齐',
@@ -10,10 +10,10 @@
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
- import { createDiscover } from './discover.js'
16
+ import { createDiscover, normalizeTaste } from './discover.js'
17
17
  import { detectLanguage } from './diversity.js'
18
18
  import { topArtists, planExploreSlots, normKey, assembleBatch, exploreCandidateOk } from './quota.js'
19
19
  import { interpretStyle, styleQueryPlan, fallbackPlan, FALLBACK_GENRES } from './style.js'
@@ -26,8 +26,10 @@ const RECENT_RECOMMENDED_MAX = 40 // 防重复:最近 2 批(20 首/批)推
26
26
  const STYLE_LIMIT = 8 // 风格搜索结果上限
27
27
  const BOOTSTRAP_HISTORY_EVENTS = 3 // 播放事件少于此值视为历史不足(D3 冷启动探索批次)
28
28
 
29
- export function createReco({ history, library, storage, config = {}, logger, verifier: verifierOverride, discover: discoverOverride, images: imagesOverride } = {}) {
29
+ export function createReco({ history, library, storage, config = {}, logger, verifier: verifierOverride, discover: discoverOverride, images: imagesOverride, now: nowOverride } = {}) {
30
30
  const warn = (msg) => logger?.warn?.(msg)
31
+ // 十期:可注入时钟(单测模拟跨天/当日复用);默认真实时间
32
+ const now = typeof nowOverride === 'function' ? nowOverride : () => Date.now()
31
33
  // verifier/discover/images 可注入(单测用假实现离线跑全流程);生产缺省即真实模块
32
34
  const verifier = verifierOverride ?? createVerifier({ storage, logger })
33
35
  const discover = discoverOverride ?? createDiscover({ storage, logger })
@@ -36,6 +38,22 @@ export function createReco({ history, library, storage, config = {}, logger, ver
36
38
  const historyFile = join(storage.dataDir, 'reco-history.json')
37
39
  let generating = false
38
40
  let sectionsBusy = false
41
+ // 十期:三栏当日快照(只落本地 cache/,不进 history 数据)
42
+ const dailyFile = join(storage.dataDir, 'cache', 'reco', 'sections-daily.json')
43
+
44
+ function localDateKey(ts) {
45
+ const d = new Date(ts)
46
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
47
+ }
48
+
49
+ async function readDailySections() {
50
+ const saved = await readJson(dailyFile, null)
51
+ return saved && saved.date === localDateKey(now()) ? saved : null
52
+ }
53
+
54
+ async function writeDailySections(value) {
55
+ await writeJson(dailyFile, value)
56
+ }
39
57
 
40
58
  async function readJson(file, fallback) {
41
59
  try {
@@ -46,6 +64,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
46
64
  }
47
65
 
48
66
  async function writeJson(file, value) {
67
+ await mkdir(dirname(file), { recursive: true })
49
68
  const tmp = `${file}.tmp-${process.pid}`
50
69
  await writeFile(tmp, JSON.stringify(value), 'utf8')
51
70
  await rename(tmp, file)
@@ -303,8 +322,20 @@ export function createReco({ history, library, storage, config = {}, logger, ver
303
322
  let profile = cached?.data ?? null
304
323
  let message = null
305
324
  if (!profile) {
306
- profile = await liveWikiProfile(a.name)
307
- if (!profile) message = '暂无该歌手资料'
325
+ const live = await liveWikiProfile(a.name)
326
+ if (live) {
327
+ // 九期点4:live 维基兜底成功即持久化(与 metadata/artist.js 同一缓存格式/路径,两条路径共享,
328
+ // TTL 内重开零网络拉取);写失败只告警,不影响本次返回。
329
+ const data = { name: a.name, ...live }
330
+ try {
331
+ await writeJson(cacheFile, { version: 1, data, fetchedAt: Date.now() })
332
+ } catch (err) {
333
+ warn?.(`dsh-music: 回写歌手缓存失败 ${a.name}: ${err.message}`)
334
+ }
335
+ profile = data
336
+ } else {
337
+ message = '暂无该歌手资料'
338
+ }
308
339
  }
309
340
  if (typeof library.ensureScanned === 'function') await library.ensureScanned()
310
341
  const tracks = library.snapshot()?.tracks ?? []
@@ -393,7 +424,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
393
424
  libraryKeys, topArtistSet, profileValues, exploreSlots: plan.slots, similarCount: needSimilar,
394
425
  })
395
426
  if (picked.length < needSimilar + EXPLORE_SLOTS) {
396
- throw new Error(`合格候选不足(装配 ${picked.length}/10),请稍后重试生成`)
427
+ throw new Error(`合格候选不足(装配 ${picked.length}/${needSimilar + EXPLORE_SLOTS}),请稍后重试生成`)
397
428
  }
398
429
 
399
430
  // ---- 逐首联网核实;失败用同类替补(保证输出全部核实过)----
@@ -454,7 +485,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
454
485
  }
455
486
 
456
487
  const batch = {
457
- generatedAt: Date.now(),
488
+ generatedAt: now(),
458
489
  engine: 'traditional-musicbrainz',
459
490
  bootstrap,
460
491
  note: bootstrap ? '探索批次:基于公众热门流派与场景生成,收听增长后会逐步个性化' : null,
@@ -478,7 +509,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
478
509
  ...(Array.isArray(state.recentRecommended) ? state.recentRecommended : []),
479
510
  ...finalItems.map((i) => normKey(i.artist, i.title)),
480
511
  ].slice(-RECENT_RECOMMENDED_MAX),
481
- updatedAt: Date.now(),
512
+ updatedAt: now(),
482
513
  })
483
514
  const batches = await readJson(historyFile, [])
484
515
  batches.push(batch)
@@ -489,6 +520,128 @@ export function createReco({ history, library, storage, config = {}, logger, ver
489
520
  /** 三栏目入口:today(7+3 当日批次) + artist(高频歌手扩相似) + new(新增/近期发行)。
490
521
  * 当日已有批次则复用(todayFromCache=true),否则生成新批次(推进轮换)。
491
522
  * 全部候选逐首 MB 核实;item 结构同 /api/reco,可直接传 POST /api/download。 */
523
+ /** today 栏:同自然日且数量达标(>=14+6,冷启动探索批次>=6)复用最近批次;否则生成新批次。 */
524
+ async function computeTodayColumn({ taste, force = false }) {
525
+ const batches = await readJson(historyFile, [])
526
+ const lastBatch = Array.isArray(batches) && batches.length > 0 ? batches[batches.length - 1] : null
527
+ // D3:探索批次只有 ≥6 首,但同日内仍应复用(否则每次进推荐页都重新生成)
528
+ const sizeOk = (lastBatch?.items ?? []).length >= SIMILAR_SLOTS + EXPLORE_SLOTS || lastBatch?.bootstrap === true
529
+ if (!force && lastBatch && sameLocalDay(lastBatch.generatedAt, now()) && sizeOk) {
530
+ const today = lastBatch.items ?? []
531
+ // 旧批次(三期生成,无 coverUrl):复用时就地回填并写回批次
532
+ if (today.some((i) => !i.coverUrl)) {
533
+ let changed = false
534
+ for (const it of today) {
535
+ if (it.coverUrl) continue
536
+ let coverUrl = null
537
+ if (it.trackId) {
538
+ const rec = library.getRecord?.(it.trackId)
539
+ if (rec?.meta?.hasCover) coverUrl = `/dsh-music/cover/${it.trackId}`
540
+ }
541
+ if (!coverUrl) coverUrl = await images.coverUrl({ artist: it.artist, title: it.title })
542
+ if (coverUrl) {
543
+ it.coverUrl = coverUrl
544
+ changed = true
545
+ }
546
+ }
547
+ if (changed) {
548
+ lastBatch.items = today
549
+ await writeJson(historyFile, batches)
550
+ }
551
+ }
552
+ return { items: today, generatedAt: lastBatch.generatedAt, bootstrap: Boolean(lastBatch.bootstrap), note: lastBatch.note ?? null, reused: true }
553
+ }
554
+ const batch = await generate(taste ? { taste } : {})
555
+ return { items: batch.items, generatedAt: batch.generatedAt, bootstrap: Boolean(batch.bootstrap), note: batch.note ?? null, reused: false }
556
+ }
557
+
558
+ /** artist 栏:20 位歌手对象 + 真实图;推进歌手轮换游标。 */
559
+ async function computeArtistColumn({ seedArtists, state }) {
560
+ const artistResult = await discover.buildArtistList({
561
+ seedArtists, exclude: new Set(seedArtists), cursor: Number(state.cursors?.artist) || 0, limit: 20,
562
+ })
563
+ const imgMap = await images.artistImages(artistResult.artists.map((a) => a.name))
564
+ const items = artistResult.artists.map((a) => ({ ...a, imageUrl: imgMap.get(a.name)?.thumbnail ?? null }))
565
+ await writeJson(stateFile, {
566
+ ...state,
567
+ cursors: { ...(state.cursors ?? {}), artist: artistResult.cursor },
568
+ updatedAt: now(),
569
+ })
570
+ return { items, generatedAt: now() }
571
+ }
572
+
573
+ /** new 栏:近 180 天真新发行,逐首核实;排除防重复名单与不喜欢。 */
574
+ async function computeNewColumn({ taste, profile, seedArtists, libraryKeys, recentKeys, tracks, todayItems, state }) {
575
+ const recentRecommended = new Set(Array.isArray(state.recentRecommended) ? state.recentRecommended : [])
576
+ const used = new Set([...recentRecommended, ...todayItems.map((i) => normKey(i.artist, i.title))])
577
+ const disliked = await readDislikes()
578
+ const tasteGenres = (taste?.genres?.length ? taste.genres : profile.genres).slice(0, 4)
579
+ const newCands = (await discover.buildNewCandidates({
580
+ tracks, getRecord: (id) => library.getRecord(id), seedArtists, libraryKeys, recentKeys,
581
+ extraKeys: used, tasteGenres, dislikedKeys: disliked.keys, dislikedArtists: disliked.artists, limit: 20,
582
+ })).filter((c) => !disliked.keys.has(normKey(c.artist, c.title)))
583
+ const items = await verifyToItems(newCands, { limit: 20, category: 'new', usedKeys: used })
584
+ return { items, generatedAt: now() }
585
+ }
586
+
587
+ function sectionsPayload({ today, artist, newColumn, fromCache, generatedAt, refreshed }) {
588
+ return {
589
+ today: today.items,
590
+ artist: artist.items,
591
+ new: newColumn.items,
592
+ generatedAt: generatedAt ?? now(),
593
+ todayGeneratedAt: today.generatedAt,
594
+ todayFromCache: Boolean(fromCache.today),
595
+ // 十期:每栏是否来自当日缓存(前端据此判断是否需要请求新数据)
596
+ fromCache: { today: Boolean(fromCache.today), artist: Boolean(fromCache.artist), new: Boolean(fromCache.new) },
597
+ exploreOnly: Boolean(today.bootstrap),
598
+ note: today.note ?? null,
599
+ ...(refreshed ? { refreshed } : {}),
600
+ }
601
+ }
602
+
603
+ /** 计算三栏(sections 首调与 refresh 共用);force=指定栏强制重算,其余取当日快照。
604
+ * 任一步抛错都不会写当日快照——失败当日可重试。 */
605
+ async function computeSections({ taste, daily = null, force = null } = {}) {
606
+ const { events } = await history.read({ limit: HISTORY_LIMIT })
607
+ if (typeof library.ensureScanned === 'function') await library.ensureScanned()
608
+ const snap = library.snapshot()
609
+ const tracks = snap?.tracks ?? []
610
+ const { seedArtists, libraryKeys, recentKeys, profile } = await buildProfile(events, tracks)
611
+
612
+ const fromCache = {
613
+ today: Array.isArray(daily?.today?.items),
614
+ artist: Array.isArray(daily?.artist?.items),
615
+ new: Array.isArray(daily?.new?.items),
616
+ }
617
+
618
+ let today = daily?.today
619
+ if (force === 'today' || !fromCache.today) {
620
+ fromCache.today = false
621
+ today = await computeTodayColumn({ taste, force: force === 'today' })
622
+ fromCache.today = Boolean(today.reused)
623
+ }
624
+
625
+ // generate() 会写轮换游标/防重复名单,必须在其后重读 state
626
+ let state = await readJson(stateFile, {})
627
+ let artist = daily?.artist
628
+ if (force === 'artist' || !fromCache.artist) {
629
+ fromCache.artist = false
630
+ artist = await computeArtistColumn({ seedArtists, state })
631
+ state = await readJson(stateFile, {})
632
+ }
633
+
634
+ let newColumn = daily?.new
635
+ if (force === 'new' || !fromCache.new) {
636
+ fromCache.new = false
637
+ newColumn = await computeNewColumn({ taste, profile, seedArtists, libraryKeys, recentKeys, tracks, todayItems: today.items, state })
638
+ }
639
+
640
+ const saved = { date: localDateKey(now()), generatedAt: now(), today, artist, new: newColumn }
641
+ await writeDailySections(saved)
642
+ return sectionsPayload({ today, artist, newColumn, fromCache, generatedAt: saved.generatedAt, refreshed: force ?? undefined })
643
+ }
644
+
492
645
  async function sections(options = {}) {
493
646
  const taste = options?.taste ?? undefined
494
647
  if (sectionsBusy) {
@@ -498,91 +651,36 @@ export function createReco({ history, library, storage, config = {}, logger, ver
498
651
  }
499
652
  sectionsBusy = true
500
653
  try {
501
- const { events } = await history.read({ limit: HISTORY_LIMIT })
502
- if (typeof library.ensureScanned === 'function') await library.ensureScanned()
503
- const snap = library.snapshot()
504
- const tracks = snap?.tracks ?? []
505
- const { seedArtists, libraryKeys, recentKeys, profile } = await buildProfile(events, tracks)
506
-
507
- // today:同一自然日「且数量达标(>= 14+6)」才复用最近一批;否则生成新批次(推进探索轴轮换)。
508
- // 旧版本(二期 10 首/批)的当日批次不足 20,必须重生成,否则活体会显示 10 首。
509
- const batches = await readJson(historyFile, [])
510
- const lastBatch = Array.isArray(batches) && batches.length > 0 ? batches[batches.length - 1] : null
511
- let today
512
- let todayBatch = null
513
- let todayGeneratedAt
514
- let todayFromCache = false
515
- // D3:探索批次只有 ≥6 首,但同日内仍应复用(否则每次进推荐页都重新生成)
516
- const sizeOk = (lastBatch?.items ?? []).length >= SIMILAR_SLOTS + EXPLORE_SLOTS || lastBatch?.bootstrap === true
517
- if (lastBatch && sameLocalDay(lastBatch.generatedAt, Date.now()) && sizeOk) {
518
- today = lastBatch.items ?? []
519
- todayBatch = lastBatch
520
- todayGeneratedAt = lastBatch.generatedAt
521
- todayFromCache = true
522
- // 旧批次(三期生成,无 coverUrl):复用时就地回填并写回批次——
523
- // 本地曲走曲库封面路由,其余走图片模块(有 30 天缓存),失败保持 null 由前端兜底。
524
- if (today.some((i) => !i.coverUrl)) {
525
- let changed = false
526
- for (const it of today) {
527
- if (it.coverUrl) continue
528
- let coverUrl = null
529
- if (it.trackId) {
530
- const rec = library.getRecord?.(it.trackId)
531
- if (rec?.meta?.hasCover) coverUrl = `/dsh-music/cover/${it.trackId}`
532
- }
533
- if (!coverUrl) coverUrl = await images.coverUrl({ artist: it.artist, title: it.title })
534
- if (coverUrl) {
535
- it.coverUrl = coverUrl
536
- changed = true
537
- }
538
- }
539
- if (changed) {
540
- lastBatch.items = today
541
- await writeJson(historyFile, batches)
542
- }
543
- }
544
- } else {
545
- const batch = await generate(taste ? { taste } : {})
546
- today = batch.items
547
- todayBatch = batch
548
- todayGeneratedAt = batch.generatedAt
654
+ const daily = await readDailySections()
655
+ // 当日快照完整 → 零重算直接返回(不读历史、不调 discover/verify)
656
+ if (daily && Array.isArray(daily.today?.items) && Array.isArray(daily.artist?.items) && Array.isArray(daily.new?.items)) {
657
+ return sectionsPayload({
658
+ today: daily.today, artist: daily.artist, newColumn: daily.new,
659
+ fromCache: { today: true, artist: true, new: true }, generatedAt: daily.generatedAt,
660
+ })
549
661
  }
662
+ return await computeSections({ taste, daily })
663
+ } finally {
664
+ sectionsBusy = false
665
+ }
666
+ }
550
667
 
551
- // 状态在 generate() 之后重读,避免覆盖其写入的轮换游标/防重复名单
552
- const state = await readJson(stateFile, {})
553
- const recentRecommended = new Set(Array.isArray(state.recentRecommended) ? state.recentRecommended : [])
554
- const usedKeys = new Set([...recentRecommended, ...today.map((i) => normKey(i.artist, i.title))])
555
-
556
- // artist:20 位歌手对象(高频歌手的关系歌手 + 同标签热门歌手补充,含歌手页核实记录)
557
- const artistResult = await discover.buildArtistList({
558
- seedArtists, exclude: new Set(seedArtists), cursor: Number(state.cursors?.artist) || 0, limit: 20,
559
- })
560
- // 歌手真实图(维基 action API 批量一次请求,失败 null 由前端兜底)
561
- const imgMap = await images.artistImages(artistResult.artists.map((a) => a.name))
562
- const artist = artistResult.artists.map((a) => ({ ...a, imageUrl: imgMap.get(a.name)?.thumbnail ?? null }))
563
-
564
- // new:真正的新发行(近 180 天,八期①)——高频歌手/相似歌手/口味流派来源;本地刚入库不算新歌
565
- const disliked = await readDislikes()
566
- const tasteGenres = (taste?.genres?.length ? taste.genres : profile.genres).slice(0, 4)
567
- const usedForNew = new Set(usedKeys)
568
- const newCands = (await discover.buildNewCandidates({
569
- tracks, getRecord: (id) => library.getRecord(id), seedArtists, libraryKeys, recentKeys, extraKeys: usedForNew,
570
- tasteGenres, dislikedKeys: disliked.keys, dislikedArtists: disliked.artists, limit: 20,
571
- })).filter((c) => !disliked.keys.has(normKey(c.artist, c.title)))
572
- const fresh = await verifyToItems(newCands, { limit: 20, category: 'new', usedKeys: usedForNew })
573
-
574
- // 持久化歌手轮换游标(merge 现有 state,不覆盖其余字段)
575
- await writeJson(stateFile, {
576
- ...state,
577
- cursors: { ...(state.cursors ?? {}), artist: artistResult.cursor },
578
- updatedAt: Date.now(),
579
- })
580
- return {
581
- today, artist, new: fresh, generatedAt: Date.now(), todayGeneratedAt, todayFromCache,
582
- // D3 明示:今日栏为冷启动「探索批次」(历史不足时),前端可据此显示说明
583
- exploreOnly: Boolean(todayBatch?.bootstrap),
584
- note: todayBatch?.note ?? null,
585
- }
668
+ /** 十期 stage1:单栏主动重推(只重算指定栏,其余取当日快照;跨天/首调时缺失栏补齐)。 */
669
+ async function refreshSections(axis, options = {}) {
670
+ if (!['today', 'artist', 'new'].includes(axis)) {
671
+ const err = new Error('axis 必须是 today/artist/new 之一')
672
+ err.code = 'BAD_REQUEST'
673
+ throw err
674
+ }
675
+ if (sectionsBusy) {
676
+ const err = new Error('推荐栏目正在生成中,请稍候')
677
+ err.code = 'BUSY'
678
+ throw err
679
+ }
680
+ sectionsBusy = true
681
+ try {
682
+ const daily = await readDailySections()
683
+ return await computeSections({ taste: options?.taste, daily, force: axis })
586
684
  } finally {
587
685
  sectionsBusy = false
588
686
  }
@@ -591,6 +689,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
591
689
  return {
592
690
  generate,
593
691
  sections,
692
+ refreshSections,
594
693
  styleSearch,
595
694
  artistPage,
596
695
  artistAvatar,
@@ -625,6 +724,35 @@ export function registerRecoRoutes(webServer, { reco, logger }) {
625
724
  return genres.length || languages.length ? { genres, languages } : undefined
626
725
  }
627
726
 
727
+ /** 十期:refresh 的 axis 走 JSON body {axis}(也兼容 ?axis=),便于客户端 POST。 */
728
+ const readJsonBody = (req) => new Promise((resolve, reject) => {
729
+ if (typeof req.on !== 'function') return resolve({})
730
+ let raw = ''
731
+ let done = false
732
+ req.on('data', (chunk) => {
733
+ if (done) return
734
+ raw += chunk
735
+ if (raw.length > 4096) {
736
+ done = true
737
+ reject(Object.assign(new Error('请求体过大'), { code: 'BAD_REQUEST' }))
738
+ }
739
+ })
740
+ req.on('end', () => {
741
+ if (done) return
742
+ done = true
743
+ if (!raw.trim()) return resolve({})
744
+ try {
745
+ const parsed = JSON.parse(raw)
746
+ resolve(parsed && typeof parsed === 'object' ? parsed : {})
747
+ } catch {
748
+ reject(Object.assign(new Error('请求体不是合法 JSON'), { code: 'BAD_REQUEST' }))
749
+ }
750
+ })
751
+ req.on('error', (err) => {
752
+ if (!done) { done = true; reject(err) }
753
+ })
754
+ })
755
+
628
756
  const disposers = []
629
757
  disposers.push(webServer.register({
630
758
  kind: 'exact',
@@ -671,6 +799,27 @@ export function registerRecoRoutes(webServer, { reco, logger }) {
671
799
  }
672
800
  },
673
801
  }))
802
+ disposers.push(webServer.register({
803
+ kind: 'exact',
804
+ path: '/dsh-music/api/reco/sections/refresh',
805
+ handler: async (req, res) => {
806
+ if (req.method !== 'POST') return sendJson(res, 405, { error: '方法不允许' })
807
+ try {
808
+ const body = await readJsonBody(req)
809
+ const url = new URL(req.url ?? '/', 'http://dsh-music.local')
810
+ const axis = String(body?.axis ?? url.searchParams.get('axis') ?? '').trim()
811
+ const taste = body?.taste ? normalizeTaste(body.taste) : parseTaste(req)
812
+ const cleaned = taste && (taste.genres.length || taste.languages.length) ? taste : undefined
813
+ if (!axis) return sendJson(res, 400, { error: '缺少 axis(today/artist/new)' })
814
+ return sendJson(res, 200, await reco.refreshSections(axis, cleaned ? { taste: cleaned } : {}))
815
+ } catch (err) {
816
+ if (err.code === 'BUSY') return sendJson(res, 409, { error: err.message })
817
+ if (err.code === 'BAD_REQUEST') return sendJson(res, 400, { error: err.message })
818
+ warn(`dsh-music: 单栏重推服务错误: ${err.message}`)
819
+ return sendJson(res, 502, { error: `单栏重推失败:${err.message}` })
820
+ }
821
+ },
822
+ }))
674
823
  disposers.push(webServer.register({
675
824
  kind: 'exact',
676
825
  path: '/dsh-music/api/reco/artist-image',
@@ -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/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.4.0",
6
+ "version": "0.6.0",
7
7
  "private": false,
8
8
  "license": "MIT",
9
9
  "author": "vicyangworld",