@vicyangorg/dsh-music 0.5.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.
package/client/index.js CHANGED
@@ -281,6 +281,10 @@ window.__ModuleLoader__.load({
281
281
  recoGenerate: '生成推荐',
282
282
  recoRegenerate: '换一批',
283
283
  recoGenerating: '正在生成推荐(每首候选先联网核实,约需半分钟)…',
284
+ recoRefresh: '重新推荐本栏',
285
+ recoRefreshHint: '只重算这一栏,其余两栏保持当天已固化的内容',
286
+ recoRefreshing: '正在重新推荐这一栏…',
287
+ recoRefreshBusy: '这一栏正在生成中,请稍后再试',
284
288
  recoEmptyTitle: '还没有推荐',
285
289
  recoEmptyBody: '基于你的收听历史生成一批 10 首:7 首口味相近 + 3 首强制探索(流派/语言/年代轮换),每首都先联网核实真实存在,杜绝幻觉歌曲。多听几首歌,推荐会更懂你。',
286
290
  recoError: '推荐生成失败',
@@ -547,6 +551,10 @@ window.__ModuleLoader__.load({
547
551
  recoGenerate: 'Generate',
548
552
  recoRegenerate: 'Another batch',
549
553
  recoGenerating: 'Generating recommendations (every candidate is verified online first, ~30s)…',
554
+ recoRefresh: 'Refresh this column',
555
+ recoRefreshHint: 'Recomputes only this column; the other two keep today\'s fixed snapshot',
556
+ recoRefreshing: 'Refreshing this column…',
557
+ recoRefreshBusy: 'This column is being generated — try again in a moment',
550
558
  recoEmptyTitle: 'No recommendations yet',
551
559
  recoEmptyBody: 'We build a batch of 10 from your listening history: 7 close to your taste + 3 forced explorations (genre / language / era rotation), each verified online before it shows up. Play a few more songs and it gets smarter.',
552
560
  recoError: 'Recommendations failed',
@@ -1049,7 +1057,14 @@ window.__ModuleLoader__.load({
1049
1057
  .dshm-col-head{flex:none;display:flex;align-items:center;gap:8px;padding:12px 14px 8px;}
1050
1058
  .dshm-col-title{font-size:13.5px;font-weight:680;color:var(--dsw-alias-label-primary);display:flex;align-items:center;gap:6px;}
1051
1059
  .dshm-col-count{font-size:11px;color:var(--dsw-alias-label-tertiary);}
1052
- .dshm-col-play{margin-left:auto;}
1060
+ .dshm-col-play{margin-left:0;}
1061
+ .dshm-col-actions{display:flex;align-items:center;gap:6px;margin-left:auto;}
1062
+ .dshm-col-refresh{width:26px;height:26px;padding:0;justify-content:center;color:var(--dsw-alias-label-secondary);}
1063
+ .dshm-col-refresh:hover{color:var(--dsw-alias-label-primary);}
1064
+ .dshm-col-loading{display:flex;align-items:center;gap:6px;padding:0 14px 6px;font-size:12px;color:var(--dsw-alias-label-secondary);}
1065
+ .dshm-refresh-note{color:var(--dsw-alias-label-secondary);}
1066
+ .dshm-playround-busy{background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-inverted);opacity:.7;}
1067
+ .dshm-playround .dshm-spin,.dshm-col-refresh .dshm-spin,.dshm-col-loading .dshm-spin,.dshm-row-play .dshm-spin{display:inline-block;width:12px;height:12px;border-radius:50%;border:2px solid currentColor;border-top-color:transparent;box-sizing:border-box;}
1053
1068
  .dshm-col-list{flex:1;min-height:0;overflow-y:auto;padding:2px 8px 16px;scrollbar-width:thin;scrollbar-color:var(--dsw-alias-scrollbar-bg-l2) transparent;}
1054
1069
  .dshm-srow{display:grid;grid-template-columns:38px minmax(0,1fr) auto auto auto;align-items:center;gap:10px;padding:6px;border-radius:10px;transition:background .12s;}
1055
1070
  .dshm-srow:hover{background:var(--dsw-alias-interactive-bg-hover);}
@@ -1203,6 +1218,16 @@ window.__ModuleLoader__.load({
1203
1218
  if (languages.length) parts.push('languages=' + encodeURIComponent(languages.join(',')));
1204
1219
  return parts.length ? '?' + parts.join('&') : '';
1205
1220
  }
1221
+ /* Same taste payload for POST bodies (per-column refresh). */
1222
+ function tasteBody(taste) {
1223
+ if (!taste || typeof taste !== 'object') return {};
1224
+ const genres = (taste.genres || []).filter(Boolean);
1225
+ const languages = (taste.languages || []).filter(Boolean);
1226
+ const body = {};
1227
+ if (genres.length) body.genres = genres;
1228
+ if (languages.length) body.languages = languages;
1229
+ return body;
1230
+ }
1206
1231
 
1207
1232
  async function request(path, options) {
1208
1233
  let res;
@@ -1228,6 +1253,10 @@ window.__ModuleLoader__.load({
1228
1253
  artist: (name) => request('/dsh-music/api/artist?name=' + encodeURIComponent(name)),
1229
1254
  artistImage: (name) => request('/dsh-music/api/reco/artist-image?name=' + encodeURIComponent(name)),
1230
1255
  recoSections: (taste) => request('/dsh-music/api/reco/sections' + tasteQuery(taste)),
1256
+ recoSectionsRefresh: (axis, taste) => request('/dsh-music/api/reco/sections/refresh', {
1257
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
1258
+ body: JSON.stringify(Object.assign({ axis }, tasteBody(taste))),
1259
+ }),
1231
1260
  deleteTrack: (trackId, confirm) => request('/dsh-music/api/library/delete', {
1232
1261
  method: 'POST', headers: { 'Content-Type': 'application/json' },
1233
1262
  body: JSON.stringify({ trackId, confirm: !!confirm }),
@@ -1512,7 +1541,12 @@ window.__ModuleLoader__.load({
1512
1541
  * 6c. S3 services: recommendations / downloads / sync / history
1513
1542
  * ================================================================ */
1514
1543
  function createRecoService(api) {
1515
- const store = createStore({ status: 'idle', items: [], sections: null, generatedAt: 0, stats: null, error: null, bootstrapNote: null });
1544
+ const store = createStore({
1545
+ status: 'idle', items: [], sections: null, generatedAt: 0, stats: null, error: null, bootstrapNote: null,
1546
+ fromCache: { today: false, artist: false, new: false },
1547
+ refreshing: { today: false, artist: false, new: false },
1548
+ refreshError: null, refreshBusy: false,
1549
+ });
1516
1550
  let inflight = false;
1517
1551
  async function pollUntilIdle() {
1518
1552
  for (;;) {
@@ -1565,6 +1599,8 @@ window.__ModuleLoader__.load({
1565
1599
  store.set({
1566
1600
  status: 'ready', sections, items: sections.today, generatedAt: data.generatedAt || Date.now(),
1567
1601
  error: null, bootstrapNote: data.exploreOnly ? (data.note || null) : null,
1602
+ fromCache: (data && data.fromCache) || { today: false, artist: false, new: false },
1603
+ refreshError: null, refreshBusy: false,
1568
1604
  });
1569
1605
  return true;
1570
1606
  } catch { return false; }
@@ -1580,7 +1616,41 @@ window.__ModuleLoader__.load({
1580
1616
  }
1581
1617
  } catch { /* keep empty CTA; user can still generate */ }
1582
1618
  }
1583
- return { source: store, generate, load, searchStyle: (q) => api.recoStyle(q), artistPage: (name) => api.recoArtist(name) };
1619
+ /* Per-column "recompute this column only" (十期). The Host keeps the
1620
+ * three-column daily snapshot and only regenerates the requested axis,
1621
+ * reusing the rest, so the other two columns never flicker. */
1622
+ const AXES = ['today', 'artist', 'new'];
1623
+ async function refresh(axis) {
1624
+ if (AXES.indexOf(axis) < 0 || !api.recoSectionsRefresh) return;
1625
+ const cur = store.getSnapshot();
1626
+ if (cur.refreshing[axis]) return;
1627
+ store.set({ refreshing: Object.assign({}, cur.refreshing, { [axis]: true }), refreshError: null, refreshBusy: false });
1628
+ try {
1629
+ const data = await api.recoSectionsRefresh(axis, readPrefs().taste || null);
1630
+ const prev = store.getSnapshot();
1631
+ const base = prev.sections || { today: [], artist: [], new: [] };
1632
+ const sections = {
1633
+ today: (data && data.today) || base.today || [],
1634
+ artist: (data && data.artist) || base.artist || [],
1635
+ new: (data && (data['new'] || data.newColumn)) || base['new'] || [],
1636
+ };
1637
+ store.set({
1638
+ status: 'ready', sections, items: sections.today, error: null,
1639
+ generatedAt: (data && data.generatedAt) || prev.generatedAt,
1640
+ fromCache: (data && data.fromCache) || prev.fromCache,
1641
+ refreshing: { today: false, artist: false, new: false },
1642
+ refreshError: null, refreshBusy: false,
1643
+ });
1644
+ } catch (err) {
1645
+ const msg = (err && err.message) || String(err);
1646
+ const busy = /409|正在|生成中/.test(msg);
1647
+ store.set({
1648
+ refreshing: { today: false, artist: false, new: false },
1649
+ refreshError: busy ? 'busy' : msg, refreshBusy: busy,
1650
+ });
1651
+ }
1652
+ }
1653
+ return { source: store, generate, load, refresh, searchStyle: (q) => api.recoStyle(q), artistPage: (name) => api.recoArtist(name) };
1584
1654
  }
1585
1655
 
1586
1656
  function createDownloadService(api) {
@@ -1811,6 +1881,95 @@ window.__ModuleLoader__.load({
1811
1881
  return { source: store, start, dispose };
1812
1882
  }
1813
1883
 
1884
+ /* ================================================================
1885
+ * 6b. Warm service —「缓存转圈」反馈(十期②)
1886
+ * pending 里为正在缓存的行;试听缓存同一时刻只能跑一首(Host 单 job +
1887
+ * 共享管线锁),所以这里串行预热:整栏播放时整栏行同时转圈,每首就绪
1888
+ * 立即解除该行转圈并追加到队列(首首就绪即开播)。同一时间只跑一轮,
1889
+ * 转圈期间再点任何一首都被忽略,避免连点重复下载。
1890
+ * ================================================================ */
1891
+ function createWarmService(preview, player) {
1892
+ const store = createStore({ pending: {}, running: false });
1893
+ function isPending(item) {
1894
+ return !!store.getSnapshot().pending[likeKey(item)];
1895
+ }
1896
+ function mark(items, on) {
1897
+ const next = Object.assign({}, store.getSnapshot().pending);
1898
+ for (const it of items || []) {
1899
+ const key = likeKey(it);
1900
+ if (on) next[key] = true;
1901
+ else delete next[key];
1902
+ }
1903
+ store.set({ pending: next });
1904
+ }
1905
+ function trackOf(item, audioUrl) {
1906
+ return {
1907
+ id: 'preview:' + likeKey(item),
1908
+ title: item.title, artist: item.artist, album: item.album,
1909
+ coverUrl: item.coverUrl || null, audioUrl, duration: null,
1910
+ };
1911
+ }
1912
+ function warmOne(item) {
1913
+ return new Promise((resolve) => { preview.start(item, (res) => resolve(res || {})); });
1914
+ }
1915
+ function handle(item, res) {
1916
+ if (!res || !res.audioUrl) return;
1917
+ const tr = trackOf(item, res.audioUrl);
1918
+ if (!player.source.getSnapshot().track) player.playTracks([tr], 0);
1919
+ else player.appendTrack(tr);
1920
+ }
1921
+ /* Whole column: local hits start instantly, the rest warm serially. */
1922
+ async function playList(items, findLocal) {
1923
+ if (store.getSnapshot().running) return;
1924
+ const list = items || [];
1925
+ const localTracks = [];
1926
+ const remote = [];
1927
+ for (const it of list) {
1928
+ if (!it) continue;
1929
+ const lc = findLocal ? findLocal(it) : null;
1930
+ if (lc) {
1931
+ if (!localTracks.some((tr) => tr.id === lc.id)) localTracks.push(lc);
1932
+ } else if (it.verification) {
1933
+ remote.push(it);
1934
+ }
1935
+ }
1936
+ if (localTracks.length) player.playTracks(localTracks, 0);
1937
+ if (!remote.length) return;
1938
+ mark(remote, true);
1939
+ store.set({ running: true });
1940
+ let firstError = null;
1941
+ try {
1942
+ for (const it of remote) {
1943
+ const res = await warmOne(it);
1944
+ mark([it], false);
1945
+ if (!res.audioUrl && res.error && !firstError) firstError = res.error;
1946
+ handle(it, res);
1947
+ }
1948
+ } finally {
1949
+ mark(remote, false);
1950
+ store.set({ running: false });
1951
+ }
1952
+ return { error: firstError };
1953
+ }
1954
+ /* Single row: only that row spins. */
1955
+ async function playOne(item) {
1956
+ if (store.getSnapshot().running) return null;
1957
+ mark([item], true);
1958
+ store.set({ running: true });
1959
+ let err = null;
1960
+ try {
1961
+ const res = await warmOne(item);
1962
+ if (res && res.error) err = res.error;
1963
+ handle(item, res);
1964
+ } finally {
1965
+ mark([item], false);
1966
+ store.set({ running: false });
1967
+ }
1968
+ return err ? { error: err } : null;
1969
+ }
1970
+ return { source: store, isPending, playList, playOne };
1971
+ }
1972
+
1814
1973
  /* ================================================================
1815
1974
  * 7. Player engine — singleton audio, survives panel navigation
1816
1975
  * ================================================================ */
@@ -1943,8 +2102,18 @@ window.__ModuleLoader__.load({
1943
2102
  syncHost({ trackId: queue[index].id, queue: queue.map((tr) => tr.id).filter(Boolean) });
1944
2103
  }
1945
2104
 
1946
- function jumpTo(index) {
1947
- const { queue } = snap();
2105
+ /* Append one ready track without interrupting what plays now (十期②:
2106
+ * 整栏逐首缓存,就绪一首追加一首,队列自然续播). */
2107
+ function appendTrack(tr) {
2108
+ if (!tr || !tr.audioUrl) return;
2109
+ const snapNow = snap();
2110
+ if (!snapNow.track) { playTracks([tr], 0); return; }
2111
+ const queue = [...snapNow.queue, tr];
2112
+ set({ queue });
2113
+ syncHost({ queue: queue.map((x) => (x && x.id) || null).filter(Boolean) });
2114
+ }
2115
+
2116
+ function jumpTo(index) { const { queue } = snap();
1948
2117
  if (index < 0 || index >= queue.length) return;
1949
2118
  report(snap().track, true);
1950
2119
  set({ queueIndex: index });
@@ -2123,6 +2292,7 @@ window.__ModuleLoader__.load({
2123
2292
  return {
2124
2293
  source: store,
2125
2294
  playTracks,
2295
+ appendTrack,
2126
2296
  playAll: (tracks, opts) => playTracks(tracks, 0, opts),
2127
2297
  jumpTo,
2128
2298
  toggle,
@@ -2486,7 +2656,7 @@ window.__ModuleLoader__.load({
2486
2656
  }, h(IconThumbDown, { size: 15, style: disliked ? { fill: 'currentColor' } : undefined }));
2487
2657
  }
2488
2658
 
2489
- function TrackRow({ track, index, isCurrent, playing, onPlay, onDelete, onReveal, onOpenArtist, likes, useLikes, t, muted }) {
2659
+ function TrackRow({ track, index, isCurrent, playing, onPlay, onDelete, onReveal, onOpenArtist, likes, useLikes, t, muted, pending }) {
2490
2660
  return h('div', {
2491
2661
  className: cx('dshm-row', isCurrent && 'dshm-row-current', muted && 'dshm-row-off'),
2492
2662
  role: 'button', tabIndex: 0,
@@ -2516,7 +2686,8 @@ window.__ModuleLoader__.load({
2516
2686
  onDelete ? h('span', { className: 'dshm-row-actions', onClick: (e) => e.stopPropagation() },
2517
2687
  h(IconButton, { label: t('revealTrack'), onClick: (e) => { e.stopPropagation(); onReveal(track); } }, h(IconDisc, { size: 14 })),
2518
2688
  h(IconButton, { label: t('deleteTrack'), onClick: (e) => { e.stopPropagation(); onDelete(track); } }, h(IconClose, { size: 14 }))) : null,
2519
- h('span', { className: 'dshm-row-play', 'aria-hidden': true }, h(IconPlay, { size: 15 })));
2689
+ h('span', { className: cx('dshm-row-play', pending && 'dshm-playround-busy'), 'aria-hidden': true },
2690
+ pending ? h('span', { className: 'dshm-spin' }) : h(IconPlay, { size: 15 })));
2520
2691
  }
2521
2692
 
2522
2693
  /* ================================================================
@@ -2972,7 +3143,7 @@ window.__ModuleLoader__.load({
2972
3143
 
2973
3144
  /* V3 helpers: shared play-or-preview flow (preview never enters the
2974
3145
  * library; only ♥-like downloads it — the Host handles that on like). */
2975
- function playSong(item, player, tracks, preview, setNotice, t) {
3146
+ function playSong(item, player, tracks, preview, setNotice, t, warm) {
2976
3147
  const local = (item.trackId && tracks.find((tr) => tr.id === item.trackId))
2977
3148
  || tracks.find((tr) =>
2978
3149
  normalizeZh(tr.artist) === normalizeZh(item.artist) &&
@@ -2983,6 +3154,14 @@ window.__ModuleLoader__.load({
2983
3154
  return;
2984
3155
  }
2985
3156
  if (!item.verification) { setNotice(t('previewNoVerify')); return; }
3157
+ setNotice('');
3158
+ if (warm) {
3159
+ /* 十期②:该行 ▶ 变转圈直到缓存就绪;运行中再点被 warm 内部忽略。 */
3160
+ warm.playOne(item).then((res) => {
3161
+ if (res && res.error) setNotice(t('previewFail') + ':' + res.error);
3162
+ });
3163
+ return;
3164
+ }
2986
3165
  setNotice(t('previewLoading'));
2987
3166
  preview.start(item, (res) => {
2988
3167
  if (res.error) { setNotice(t('previewFail') + ':' + res.error); return; }
@@ -3030,8 +3209,10 @@ window.__ModuleLoader__.load({
3030
3209
  return h(Thumb, { src: url || null, size: size || 20, round: true, glyph: IconNote });
3031
3210
  }
3032
3211
 
3033
- function SongRow({ t, item, likes, useLikes, onPlay, onOpenArtist, isCurrent, playing, showReason }) {
3212
+ function SongRow({ t, item, likes, useLikes, onPlay, onOpenArtist, isCurrent, playing, showReason, warm, useWarm }) {
3034
3213
  const liked = useLikes((st) => !!st.keys[likeKey(item)]);
3214
+ /* 十期②:该行的缓存转圈态由 warm store 驱动(整栏播放时整栏一起转)。 */
3215
+ const pending = warm && useWarm ? !!useWarm((st) => !!(st.pending && st.pending[likeKey(item)])) : false;
3035
3216
  return h('div', { className: cx('dshm-srow', isCurrent && 'dshm-row-current') },
3036
3217
  h(Thumb, { src: item.coverUrl, size: 38 }),
3037
3218
  h('div', {
@@ -3061,11 +3242,15 @@ window.__ModuleLoader__.load({
3061
3242
  }, h(IconHeart, { size: 15, style: liked ? { fill: 'currentColor' } : undefined })),
3062
3243
  likes ? h(DislikeButton, { t, item, likes, useLikes }) : null,
3063
3244
  h('button', {
3064
- type: 'button', className: 'dshm-playround',
3065
- 'aria-label': isCurrent && playing ? t('pause') : t('play'),
3066
- title: isCurrent && playing ? t('pause') : t('previewLabel'),
3245
+ type: 'button', className: cx('dshm-playround', pending && 'dshm-playround-busy'),
3246
+ 'aria-label': pending ? t('previewLoading') : (isCurrent && playing ? t('pause') : t('play')),
3247
+ 'aria-busy': pending ? 'true' : undefined,
3248
+ disabled: !!pending,
3249
+ title: pending ? t('previewLoading') : (isCurrent && playing ? t('pause') : t('previewLabel')),
3067
3250
  onClick: () => onPlay(item),
3068
- }, h(isCurrent && playing ? IconPause : IconPlay, { size: 13 })));
3251
+ }, pending
3252
+ ? h('span', { className: 'dshm-spin', 'aria-hidden': true })
3253
+ : h(isCurrent && playing ? IconPause : IconPlay, { size: 13 })));
3069
3254
  }
3070
3255
 
3071
3256
  /* Artist column row: real artist/band image + name + genre hint + chevron. */
@@ -3082,7 +3267,7 @@ window.__ModuleLoader__.load({
3082
3267
  h('span', { className: 'dshm-arow-arrow', 'aria-hidden': true }, '›'));
3083
3268
  }
3084
3269
 
3085
- function RecoView({ t, reco, download, player, library, likes, preview, history, openArtistPage, useReco, useDownload, useLibrary, useLikes, usePlayer, useHistory }) {
3270
+ function RecoView({ t, reco, download, player, library, likes, preview, history, openArtistPage, warm, useReco, useDownload, useLibrary, useLikes, usePlayer, useHistory, useWarm }) {
3086
3271
  const s = useReco((st) => st);
3087
3272
  const histStats = useHistory ? useHistory((st) => st.stats) : null;
3088
3273
  const coldStart = !(histStats && histStats.totalPlays > 0);
@@ -3120,7 +3305,7 @@ window.__ModuleLoader__.load({
3120
3305
  normalizeZh(tr.title) === normalizeZh(item.title));
3121
3306
  }
3122
3307
  function onPlay(item) {
3123
- playSong(item, player, tracks, preview, setNotice, t);
3308
+ playSong(item, player, tracks, preview, setNotice, t, warm);
3124
3309
  }
3125
3310
  /* Clicking a row queues the whole visible list (deduped local matches)
3126
3311
  * and jumps straight to the clicked song; preview-only items fall back
@@ -3137,7 +3322,14 @@ window.__ModuleLoader__.load({
3137
3322
  if (localTracks.length) player.playTracks(localTracks, at);
3138
3323
  else if (list.length) onPlay(item || list[0]);
3139
3324
  }
3140
- function playColumn(list) { playListFrom(list, null); }
3325
+ /* 「播放本栏」:本地命中的立即入队,未入库的整栏一起转圈、串行预热,
3326
+ * 就绪一首追加一首(首首就绪即开播)。 */
3327
+ function playColumn(list) {
3328
+ if (!warm) { playListFrom(list, null); return; }
3329
+ warm.playList(list, findLocal).then((res) => {
3330
+ if (res && res.error) setNotice(t('previewFail') + ':' + res.error);
3331
+ });
3332
+ }
3141
3333
 
3142
3334
  const sections = s.sections || { today: s.items, artist: [], new: [] };
3143
3335
  const styleActive = styleState.status !== 'idle';
@@ -3150,15 +3342,35 @@ window.__ModuleLoader__.load({
3150
3342
  if (!list.length) return h('div', { className: 'dshm-lyrics-hint' }, t('recoSectionEmpty'));
3151
3343
  return list.map((item, i) => h(SongRow, {
3152
3344
  key: i, t, item, likes, useLikes, onPlay: (it) => playListFrom(list, it), onOpenArtist: openArtistPage, showReason,
3153
- isCurrent: isCur(item), playing,
3345
+ isCurrent: isCur(item), playing, warm, useWarm,
3154
3346
  }));
3155
3347
  }
3156
- function column(headKey, icon, list, extraHead) {
3348
+ /* 十期:每栏各自的「重新推荐」——只重算本栏,刷新中仅该栏转圈。 */
3349
+ function colRefresh(axis) {
3350
+ const refreshing = s.refreshing || {};
3351
+ const busy = !!refreshing[axis];
3352
+ return h('button', {
3353
+ type: 'button', className: cx('dshm-chipbtn dshm-col-refresh', busy && 'dshm-chipbtn-busy'),
3354
+ disabled: busy, title: t('recoRefreshHint'), 'aria-label': t('recoRefresh'),
3355
+ 'aria-busy': busy ? 'true' : undefined,
3356
+ onClick: () => reco.refresh(axis),
3357
+ }, busy
3358
+ ? h('span', { className: 'dshm-spin', 'aria-hidden': true })
3359
+ : h(IconRefresh, { size: 12 }));
3360
+ }
3361
+ function colRefreshBanner(axis) {
3362
+ const refreshing = s.refreshing || {};
3363
+ if (!refreshing[axis]) return null;
3364
+ return h('div', { className: 'dshm-col-loading', role: 'status' },
3365
+ h('span', { className: 'dshm-spin', 'aria-hidden': true }), t('recoRefreshing'));
3366
+ }
3367
+ function column(headKey, icon, list, extraHead, axis) {
3157
3368
  return h('section', { className: 'dshm-column', key: headKey },
3158
3369
  h('div', { className: 'dshm-col-head' },
3159
3370
  h('div', { className: 'dshm-col-title' }, h(icon, { size: 14 }), t(headKey)),
3160
3371
  h('span', { className: 'dshm-col-count' }, list.length + ' ' + t('tracksUnit')),
3161
- extraHead),
3372
+ h('div', { className: 'dshm-col-actions' }, axis ? colRefresh(axis) : null, extraHead)),
3373
+ colRefreshBanner(axis),
3162
3374
  h('div', { className: 'dshm-col-list' }, songRows(list, true)));
3163
3375
  }
3164
3376
 
@@ -3241,17 +3453,24 @@ window.__ModuleLoader__.load({
3241
3453
  h('span', { className: 'dshm-explore-chip' }, t('exploreChip')),
3242
3454
  h('span', null, s.bootstrapNote))
3243
3455
  : null,
3456
+ s.refreshError
3457
+ ? h('div', { className: 'dshm-explore-note dshm-refresh-note', role: 'alert' },
3458
+ h(IconAlert, { size: 13 }),
3459
+ h('span', null, s.refreshBusy ? t('recoRefreshBusy') : s.refreshError))
3460
+ : null,
3244
3461
  h('div', { className: 'dshm-columns' },
3245
3462
  column('colToday', IconSparkles, sections.today || [],
3246
3463
  h('button', {
3247
3464
  type: 'button', className: 'dshm-chipbtn dshm-col-play',
3248
3465
  disabled: !(sections.today || []).length,
3249
3466
  onClick: () => playColumn(sections.today || []),
3250
- }, h(IconPlay, { size: 12 }), t('playColumn'))),
3467
+ }, h(IconPlay, { size: 12 }), t('playColumn')), 'today'),
3251
3468
  h('section', { className: 'dshm-column', key: 'colArtist' },
3252
3469
  h('div', { className: 'dshm-col-head' },
3253
3470
  h('div', { className: 'dshm-col-title' }, h(IconNote, { size: 14 }), t('colArtist')),
3254
- h('span', { className: 'dshm-col-count' }, (sections.artist || []).length + ' ' + t('tracksUnit'))),
3471
+ h('span', { className: 'dshm-col-count' }, (sections.artist || []).length + ' ' + t('tracksUnit')),
3472
+ h('div', { className: 'dshm-col-actions' }, colRefresh('artist'))),
3473
+ colRefreshBanner('artist'),
3255
3474
  h('div', { className: 'dshm-col-list' },
3256
3475
  (sections.artist || []).length === 0
3257
3476
  ? h('div', { className: 'dshm-lyrics-hint' }, t('recoSectionEmpty'))
@@ -3261,7 +3480,7 @@ window.__ModuleLoader__.load({
3261
3480
  type: 'button', className: 'dshm-chipbtn dshm-col-play',
3262
3481
  disabled: !(sections.new || []).length,
3263
3482
  onClick: () => playColumn(sections.new || []),
3264
- }, h(IconPlay, { size: 12 }), t('playColumn')))));
3483
+ }, h(IconPlay, { size: 12 }), t('playColumn')), 'new')));
3265
3484
  }
3266
3485
 
3267
3486
  /* Shared artist profile block (intro / news / trivia / similar), reused by
@@ -3720,7 +3939,7 @@ window.__ModuleLoader__.load({
3720
3939
  /* ================================================================
3721
3940
  * 12. Music panel (main slot): header + tabs + per-view body
3722
3941
  * ================================================================ */
3723
- function MusicPanel({ t, player, library, lyrics, reco, download, sync, history, likes, preview, openView, openArtistPage, setMiniHidden, ui, artistImages, artistPage, onboarding, useUi, useLibrary, usePlayer, useLyrics, useReco, useDownload, useSync, useHistory, useLikes, usePreview, useArtistImages, useArtistPage, useOnboarding }) {
3942
+ function MusicPanel({ t, player, library, lyrics, reco, download, sync, history, likes, preview, warm, openView, openArtistPage, setMiniHidden, ui, artistImages, artistPage, onboarding, useUi, useLibrary, usePlayer, useLyrics, useReco, useDownload, useSync, useHistory, useLikes, usePreview, useWarm, useArtistImages, useArtistPage, useOnboarding }) {
3724
3943
  const view = useUi((s) => s.view);
3725
3944
  const welcomePreview = useUi((s) => s.welcomePreview);
3726
3945
  const onboardingSnap = useOnboarding((st) => st);
@@ -3775,7 +3994,7 @@ window.__ModuleLoader__.load({
3775
3994
  const body = view === 'library'
3776
3995
  ? h(LibraryView, { t, player, library, sync, download, preview, likes, openArtistPage, artistImages, useLikes, useSync, useDownload, useLibrary, usePlayer, useArtistImages })
3777
3996
  : view === 'reco'
3778
- ? h(RecoView, { t, reco, download, player, library, likes, preview, history, openArtistPage, useReco, useDownload, useLibrary, useLikes, usePlayer, useHistory })
3997
+ ? h(RecoView, { t, reco, download, player, library, likes, preview, history, openArtistPage, warm, useReco, useDownload, useLibrary, useLikes, usePlayer, useHistory, useWarm })
3779
3998
  : view === 'artist'
3780
3999
  ? h(ArtistPageView, { t, reco, player, likes, preview, library, openView, openArtistPage, artistImages, artistPage, useUi, useLikes, useLibrary, usePlayer, useArtistImages, useArtistPage })
3781
4000
  : view === 'history'
@@ -4086,6 +4305,7 @@ window.__ModuleLoader__.load({
4086
4305
  const historyService = createHistoryService(api);
4087
4306
  const player = createPlayer(t, api);
4088
4307
  const previewService = createPreviewService(api);
4308
+ const warmService = createWarmService(previewService, player);
4089
4309
  const likesService = createLikesService(api, () => downloadService.warm());
4090
4310
  ctx.effect(() => () => {
4091
4311
  downloadService.dispose();
@@ -4153,7 +4373,7 @@ window.__ModuleLoader__.load({
4153
4373
  inject: () => ({
4154
4374
  player, library, lyrics: lyricsService, artist: artistService, artistImages: artistImageService, onboarding: onboardingService,
4155
4375
  reco: recoService, download: downloadService, sync: syncService, history: historyService,
4156
- likes: likesService, preview: previewService,
4376
+ likes: likesService, preview: previewService, warm: warmService,
4157
4377
  openView, openArtistPage, setMiniHidden, ui, artistPage: artistPageService,
4158
4378
  hooks: {
4159
4379
  player: player.source, library: library.source, ui,
@@ -4161,6 +4381,7 @@ window.__ModuleLoader__.load({
4161
4381
  reco: recoService.source, download: downloadService.source,
4162
4382
  sync: syncService.source, history: historyService.source,
4163
4383
  likes: likesService.source, preview: previewService.source,
4384
+ warm: warmService.source,
4164
4385
  },
4165
4386
  }),
4166
4387
  }, MusicPanel)), 'dsh-music: main panel');
@@ -13,7 +13,7 @@
13
13
  import { join, dirname } from 'node:path'
14
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 {
@@ -406,7 +424,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
406
424
  libraryKeys, topArtistSet, profileValues, exploreSlots: plan.slots, similarCount: needSimilar,
407
425
  })
408
426
  if (picked.length < needSimilar + EXPLORE_SLOTS) {
409
- throw new Error(`合格候选不足(装配 ${picked.length}/10),请稍后重试生成`)
427
+ throw new Error(`合格候选不足(装配 ${picked.length}/${needSimilar + EXPLORE_SLOTS}),请稍后重试生成`)
410
428
  }
411
429
 
412
430
  // ---- 逐首联网核实;失败用同类替补(保证输出全部核实过)----
@@ -467,7 +485,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
467
485
  }
468
486
 
469
487
  const batch = {
470
- generatedAt: Date.now(),
488
+ generatedAt: now(),
471
489
  engine: 'traditional-musicbrainz',
472
490
  bootstrap,
473
491
  note: bootstrap ? '探索批次:基于公众热门流派与场景生成,收听增长后会逐步个性化' : null,
@@ -491,7 +509,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
491
509
  ...(Array.isArray(state.recentRecommended) ? state.recentRecommended : []),
492
510
  ...finalItems.map((i) => normKey(i.artist, i.title)),
493
511
  ].slice(-RECENT_RECOMMENDED_MAX),
494
- updatedAt: Date.now(),
512
+ updatedAt: now(),
495
513
  })
496
514
  const batches = await readJson(historyFile, [])
497
515
  batches.push(batch)
@@ -502,6 +520,128 @@ export function createReco({ history, library, storage, config = {}, logger, ver
502
520
  /** 三栏目入口:today(7+3 当日批次) + artist(高频歌手扩相似) + new(新增/近期发行)。
503
521
  * 当日已有批次则复用(todayFromCache=true),否则生成新批次(推进轮换)。
504
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
+
505
645
  async function sections(options = {}) {
506
646
  const taste = options?.taste ?? undefined
507
647
  if (sectionsBusy) {
@@ -511,91 +651,36 @@ export function createReco({ history, library, storage, config = {}, logger, ver
511
651
  }
512
652
  sectionsBusy = true
513
653
  try {
514
- const { events } = await history.read({ limit: HISTORY_LIMIT })
515
- if (typeof library.ensureScanned === 'function') await library.ensureScanned()
516
- const snap = library.snapshot()
517
- const tracks = snap?.tracks ?? []
518
- const { seedArtists, libraryKeys, recentKeys, profile } = await buildProfile(events, tracks)
519
-
520
- // today:同一自然日「且数量达标(>= 14+6)」才复用最近一批;否则生成新批次(推进探索轴轮换)。
521
- // 旧版本(二期 10 首/批)的当日批次不足 20,必须重生成,否则活体会显示 10 首。
522
- const batches = await readJson(historyFile, [])
523
- const lastBatch = Array.isArray(batches) && batches.length > 0 ? batches[batches.length - 1] : null
524
- let today
525
- let todayBatch = null
526
- let todayGeneratedAt
527
- let todayFromCache = false
528
- // D3:探索批次只有 ≥6 首,但同日内仍应复用(否则每次进推荐页都重新生成)
529
- const sizeOk = (lastBatch?.items ?? []).length >= SIMILAR_SLOTS + EXPLORE_SLOTS || lastBatch?.bootstrap === true
530
- if (lastBatch && sameLocalDay(lastBatch.generatedAt, Date.now()) && sizeOk) {
531
- today = lastBatch.items ?? []
532
- todayBatch = lastBatch
533
- todayGeneratedAt = lastBatch.generatedAt
534
- todayFromCache = true
535
- // 旧批次(三期生成,无 coverUrl):复用时就地回填并写回批次——
536
- // 本地曲走曲库封面路由,其余走图片模块(有 30 天缓存),失败保持 null 由前端兜底。
537
- if (today.some((i) => !i.coverUrl)) {
538
- let changed = false
539
- for (const it of today) {
540
- if (it.coverUrl) continue
541
- let coverUrl = null
542
- if (it.trackId) {
543
- const rec = library.getRecord?.(it.trackId)
544
- if (rec?.meta?.hasCover) coverUrl = `/dsh-music/cover/${it.trackId}`
545
- }
546
- if (!coverUrl) coverUrl = await images.coverUrl({ artist: it.artist, title: it.title })
547
- if (coverUrl) {
548
- it.coverUrl = coverUrl
549
- changed = true
550
- }
551
- }
552
- if (changed) {
553
- lastBatch.items = today
554
- await writeJson(historyFile, batches)
555
- }
556
- }
557
- } else {
558
- const batch = await generate(taste ? { taste } : {})
559
- today = batch.items
560
- todayBatch = batch
561
- 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
+ })
562
661
  }
662
+ return await computeSections({ taste, daily })
663
+ } finally {
664
+ sectionsBusy = false
665
+ }
666
+ }
563
667
 
564
- // 状态在 generate() 之后重读,避免覆盖其写入的轮换游标/防重复名单
565
- const state = await readJson(stateFile, {})
566
- const recentRecommended = new Set(Array.isArray(state.recentRecommended) ? state.recentRecommended : [])
567
- const usedKeys = new Set([...recentRecommended, ...today.map((i) => normKey(i.artist, i.title))])
568
-
569
- // artist:20 位歌手对象(高频歌手的关系歌手 + 同标签热门歌手补充,含歌手页核实记录)
570
- const artistResult = await discover.buildArtistList({
571
- seedArtists, exclude: new Set(seedArtists), cursor: Number(state.cursors?.artist) || 0, limit: 20,
572
- })
573
- // 歌手真实图(维基 action API 批量一次请求,失败 null 由前端兜底)
574
- const imgMap = await images.artistImages(artistResult.artists.map((a) => a.name))
575
- const artist = artistResult.artists.map((a) => ({ ...a, imageUrl: imgMap.get(a.name)?.thumbnail ?? null }))
576
-
577
- // new:真正的新发行(近 180 天,八期①)——高频歌手/相似歌手/口味流派来源;本地刚入库不算新歌
578
- const disliked = await readDislikes()
579
- const tasteGenres = (taste?.genres?.length ? taste.genres : profile.genres).slice(0, 4)
580
- const usedForNew = new Set(usedKeys)
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)))
585
- const fresh = await verifyToItems(newCands, { limit: 20, category: 'new', usedKeys: usedForNew })
586
-
587
- // 持久化歌手轮换游标(merge 现有 state,不覆盖其余字段)
588
- await writeJson(stateFile, {
589
- ...state,
590
- cursors: { ...(state.cursors ?? {}), artist: artistResult.cursor },
591
- updatedAt: Date.now(),
592
- })
593
- return {
594
- today, artist, new: fresh, generatedAt: Date.now(), todayGeneratedAt, todayFromCache,
595
- // D3 明示:今日栏为冷启动「探索批次」(历史不足时),前端可据此显示说明
596
- exploreOnly: Boolean(todayBatch?.bootstrap),
597
- note: todayBatch?.note ?? null,
598
- }
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 })
599
684
  } finally {
600
685
  sectionsBusy = false
601
686
  }
@@ -604,6 +689,7 @@ export function createReco({ history, library, storage, config = {}, logger, ver
604
689
  return {
605
690
  generate,
606
691
  sections,
692
+ refreshSections,
607
693
  styleSearch,
608
694
  artistPage,
609
695
  artistAvatar,
@@ -638,6 +724,35 @@ export function registerRecoRoutes(webServer, { reco, logger }) {
638
724
  return genres.length || languages.length ? { genres, languages } : undefined
639
725
  }
640
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
+
641
756
  const disposers = []
642
757
  disposers.push(webServer.register({
643
758
  kind: 'exact',
@@ -684,6 +799,27 @@ export function registerRecoRoutes(webServer, { reco, logger }) {
684
799
  }
685
800
  },
686
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
+ }))
687
823
  disposers.push(webServer.register({
688
824
  kind: 'exact',
689
825
  path: '/dsh-music/api/reco/artist-image',
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.5.0",
6
+ "version": "0.6.0",
7
7
  "private": false,
8
8
  "license": "MIT",
9
9
  "author": "vicyangworld",