@vicyangorg/dsh-music 0.5.0 → 0.7.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/README.md +12 -8
- package/client/index.js +1960 -247
- package/docs/DETAIL.md +49 -9
- package/host/accounts.js +83 -0
- package/host/download.js +60 -18
- package/host/liked-sync.js +322 -0
- package/host/likes.js +124 -9
- package/host/main.js +27 -2
- package/host/onboarding.js +10 -4
- package/host/providers/common.js +66 -0
- package/host/providers/netease.js +266 -0
- package/host/providers/qqlogin.js +521 -0
- package/host/providers/qqmusic.js +213 -0
- package/host/reco/index.js +224 -88
- package/host/routes.js +33 -0
- package/host/source-scan.js +190 -0
- package/host/sync.js +18 -5
- package/host/t2s-extra.js +153 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QQ 音乐(只读)客户端:粘贴 Cookie 登录 + 「我喜欢」歌单。
|
|
3
|
+
*
|
|
4
|
+
* - 非官方接口,只读:不写账号、不拉音源。
|
|
5
|
+
* - 登录态只需 Cookie 里的 uin(或 wxuin)+ qm_keyst / qqmusic_key;服务端不需要 sign 的旧接口即可读到「我喜欢」。
|
|
6
|
+
* - 零外部依赖:仅 node: 内置模块。
|
|
7
|
+
*/
|
|
8
|
+
import { cleanText, fetchJson, httpError, parseCookie } from './common.js'
|
|
9
|
+
|
|
10
|
+
export const QQ_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
|
|
11
|
+
export const QQ_REFERER = 'https://y.qq.com/portal/profile.html'
|
|
12
|
+
const MUSICU = 'https://u.y.qq.com/cgi-bin/musicu.fcg'
|
|
13
|
+
const MAX_SONGS = 20000
|
|
14
|
+
const PAGE_SIZE = 300
|
|
15
|
+
|
|
16
|
+
/** QQ 系 g_tk:对 keyst 做的 32 位哈希 */
|
|
17
|
+
export function gtk(key) {
|
|
18
|
+
let hash = 5381
|
|
19
|
+
for (let i = 0; i < key.length; i++) hash += (hash << 5) + key.charCodeAt(i)
|
|
20
|
+
return hash & 0x7fffffff
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 解析粘贴的 Cookie 文本 → 登录所需字段。返回 `{ error }` 或 `{ keyst, uin, wxuin, musicid, cookie, nickname }`。
|
|
25
|
+
* `cookie` 只保留登录字段,丢掉 pgv / 埋点等噪音。
|
|
26
|
+
*/
|
|
27
|
+
/** 用户可能整段粘贴:cURL(-H 'cookie: …' / -b '…')、请求头里的 cookie: 行,或纯 Cookie 串。
|
|
28
|
+
* 先把真正的 Cookie 内容抽出来,再交给 parseCookie。 */
|
|
29
|
+
export function extractCookieText(text) {
|
|
30
|
+
const s = String(text || '')
|
|
31
|
+
/* 以 cookie: 开头(可能换行续写)→ 整段都是 Cookie,交给 parseCookie 按行拼接 */
|
|
32
|
+
if (/^\s*cookie:/i.test(s)) return s
|
|
33
|
+
const m = /-H\s+['"]cookie:\s*([^'"]+)['"]/i.exec(s)
|
|
34
|
+
|| /(?:^|\n)[ \t]*cookie:[ \t]*([^\n]+)/i.exec(s)
|
|
35
|
+
|| /(?:^|\s)-b\s+['"]([^'"]+)['"]/.exec(s)
|
|
36
|
+
return m ? m[1] : s
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function parseQQCookie(text) {
|
|
40
|
+
const pairs = parseCookie(extractCookieText(text))
|
|
41
|
+
const keyst = pairs.qqmusic_key || pairs.qm_keyst || ''
|
|
42
|
+
// uin 形如 o0123456789:去掉 o 前缀与前导零得到 QQ 号(QQ 号不以 0 开头)
|
|
43
|
+
const rawUin = pairs.qqmusic_uin || pairs.uin || ''
|
|
44
|
+
const uin = rawUin.replace(/\D/g, '').replace(/^0+(?=\d)/, '')
|
|
45
|
+
const wxuin = pairs.wxuin || ''
|
|
46
|
+
const musicid = uin || wxuin
|
|
47
|
+
if (!keyst) return { error: 'Cookie 中缺少 qm_keyst / qqmusic_key(登录态),请先登录 y.qq.com 再复制 Cookie' }
|
|
48
|
+
if (!musicid) return { error: 'Cookie 中缺少 uin / wxuin(账号标识),请先登录 y.qq.com 再复制 Cookie' }
|
|
49
|
+
const parts = [`qqmusic_key=${keyst}`, `qm_keyst=${keyst}`]
|
|
50
|
+
// 原样保留登录态字段(服务端给什么格式就回传什么),不夹带 pgv / 埋点等噪音
|
|
51
|
+
for (const key of ['uin', 'qqmusic_uin', 'wxuin', 'wxrefresh_token', 'psrf_qqaccess_token', 'psrf_qqunionid', 'psrf_musickey_createtime', 'psrf_qqopenid']) {
|
|
52
|
+
if (pairs[key]) parts.push(`${key}=${pairs[key]}`)
|
|
53
|
+
}
|
|
54
|
+
let nickname = ''
|
|
55
|
+
try {
|
|
56
|
+
nickname = cleanText(pairs.qqmusic_nick ? decodeURIComponent(pairs.qqmusic_nick) : '', 64)
|
|
57
|
+
} catch {
|
|
58
|
+
nickname = ''
|
|
59
|
+
}
|
|
60
|
+
return { keyst, uin, wxuin, musicid, cookie: parts.join('; '), nickname }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function describe(j) {
|
|
64
|
+
if (!j) return '无响应'
|
|
65
|
+
const msg = j.msg || j.message || ''
|
|
66
|
+
return `code ${j.code}${j.subcode ? '/' + j.subcode : ''}${msg ? ' ' + msg : ''}`
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isAuthFail(j) {
|
|
70
|
+
const c = Number(j && j.code)
|
|
71
|
+
return c === 1000 || c === 1001 || c === -1000 || (j && /未登录|not\s*login/i.test(String(j.msg || j.message || '')))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function createQQMusic({ fetchImpl, timeoutMs = 15000 } = {}) {
|
|
75
|
+
async function get(url, cookie) {
|
|
76
|
+
const { json } = await fetchJson(
|
|
77
|
+
url,
|
|
78
|
+
{
|
|
79
|
+
method: 'GET',
|
|
80
|
+
headers: {
|
|
81
|
+
'User-Agent': QQ_UA,
|
|
82
|
+
Accept: 'application/json, text/plain, */*',
|
|
83
|
+
Referer: QQ_REFERER,
|
|
84
|
+
Cookie: cookie,
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
fetchImpl,
|
|
88
|
+
timeoutMs,
|
|
89
|
+
)
|
|
90
|
+
return json
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function auth(authInput) {
|
|
94
|
+
const a = typeof authInput === 'string' ? parseQQCookie(authInput) : authInput
|
|
95
|
+
if (!a || a.error) throw httpError((a && a.error) || 'QQ 音乐 Cookie 无效', 400)
|
|
96
|
+
return a
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 「我喜欢」歌单:优先歌单列表里 dirid===201 的项,回退个人主页 mymusic[0] */
|
|
100
|
+
async function likedDir(authInput) {
|
|
101
|
+
const a = auth(authInput)
|
|
102
|
+
const g = gtk(a.keyst)
|
|
103
|
+
const uin = encodeURIComponent(a.musicid)
|
|
104
|
+
const j = await get(
|
|
105
|
+
`https://c.y.qq.com/rsc/fcgi-bin/fcg_user_created_diss?hostUin=0&hostuin=${uin}&sin=0&size=200&g_tk=${g}&loginUin=0&format=json&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq.json&needNewCode=0`,
|
|
106
|
+
a.cookie,
|
|
107
|
+
)
|
|
108
|
+
if (isAuthFail(j)) throw httpError('QQ 音乐 Cookie 已失效或未登录,请重新登录 y.qq.com 后复制 Cookie', 401)
|
|
109
|
+
if (!j || Number(j.code) !== 0 || !j.data) throw httpError(`获取 QQ 音乐歌单失败(${describe(j)})`, 502)
|
|
110
|
+
const fav = (Array.isArray(j.data.disslist) ? j.data.disslist : []).find((d) => d && d.dirid === 201)
|
|
111
|
+
if (fav && fav.tid) {
|
|
112
|
+
return { tid: String(fav.tid), name: cleanText(fav.diss_name, 100) || '我喜欢', songCount: Number(fav.song_cnt) || 0, nickname: cleanText(j.data.hostname, 64) || a.nickname }
|
|
113
|
+
}
|
|
114
|
+
const home = await get(
|
|
115
|
+
`https://c.y.qq.com/rsc/fcgi-bin/fcg_get_profile_homepage.fcg?g_tk=${g}&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq.json&needNewCode=0&cid=205360838&userid=${uin}&reqfrom=1`,
|
|
116
|
+
a.cookie,
|
|
117
|
+
)
|
|
118
|
+
if (isAuthFail(home)) throw httpError('QQ 音乐 Cookie 已失效或未登录,请重新登录 y.qq.com 后复制 Cookie', 401)
|
|
119
|
+
const data = home && home.data
|
|
120
|
+
const my = data && Array.isArray(data.mymusic) ? data.mymusic[0] : null
|
|
121
|
+
if (my && my.id) {
|
|
122
|
+
const nick = data.hostname || (data.creator && (data.creator.nick || data.creator.hostname)) || a.nickname
|
|
123
|
+
return { tid: String(my.id), name: '我喜欢', songCount: Number(my.num0) || 0, nickname: cleanText(nick, 64) }
|
|
124
|
+
}
|
|
125
|
+
throw httpError('未找到 QQ 音乐「我喜欢」歌单(账号可能未登录或 Cookie 已失效)', 401)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 新接口(musicu.fcg uniform_get_Dissinfo,分页,匿名可达;带 Cookie 可读私有歌单) */
|
|
129
|
+
async function songsViaMusicu(a, tid) {
|
|
130
|
+
const songs = []
|
|
131
|
+
let begin = 0
|
|
132
|
+
let total = Infinity
|
|
133
|
+
while (begin < total && songs.length < MAX_SONGS) {
|
|
134
|
+
const payload = {
|
|
135
|
+
comm: { g_tk: gtk(a.keyst), uin: a.uin ? Number(a.uin) : 0, format: 'json', inCharset: 'utf-8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0 },
|
|
136
|
+
req_0: {
|
|
137
|
+
module: 'music.srfDissInfo.aiDissInfo',
|
|
138
|
+
method: 'uniform_get_Dissinfo',
|
|
139
|
+
param: { disstid: Number(tid), song_begin: begin, song_num: PAGE_SIZE, userinfo: 1, tag: 1, orderlist: 1 },
|
|
140
|
+
},
|
|
141
|
+
}
|
|
142
|
+
const j = await get(MUSICU + '?data=' + encodeURIComponent(JSON.stringify(payload)), a.cookie)
|
|
143
|
+
const r0 = (j && j.req_0) || {}
|
|
144
|
+
const d = r0.data || {}
|
|
145
|
+
if (isAuthFail(j) || isAuthFail(r0) || isAuthFail(d)) throw httpError('QQ 音乐 Cookie 已失效或未登录,请重新登录 y.qq.com 后复制 Cookie', 401)
|
|
146
|
+
if (Number(r0.code) !== 0 || Number(d.code) !== 0) throw httpError(`获取 QQ 音乐「我喜欢」歌曲失败(${describe(j)} / ${describe(r0)} / ${describe(d)})`, 502)
|
|
147
|
+
const list = Array.isArray(d.songlist) ? d.songlist : []
|
|
148
|
+
songs.push(...list)
|
|
149
|
+
const n = Number(d.total_song_num ?? (d.dirinfo && d.dirinfo.song_num) ?? list.length)
|
|
150
|
+
total = Number.isFinite(n) ? n : list.length
|
|
151
|
+
if (list.length === 0) break
|
|
152
|
+
begin += list.length
|
|
153
|
+
}
|
|
154
|
+
return songs
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 旧接口兜底:一次性返回整张歌单(部分账号会被判 privacy error,失败就放弃) */
|
|
158
|
+
async function songsViaLegacy(a, tid) {
|
|
159
|
+
const j = await get(
|
|
160
|
+
`https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?type=1&json=1&utf8=1&onlysong=0&nosigned=1&disstid=${encodeURIComponent(tid)}&g_tk=${gtk(a.keyst)}&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq.json&needNewCode=0`,
|
|
161
|
+
a.cookie,
|
|
162
|
+
)
|
|
163
|
+
if (isAuthFail(j)) throw httpError('QQ 音乐 Cookie 已失效或未登录,请重新登录 y.qq.com 后复制 Cookie', 401)
|
|
164
|
+
const cd = j && Array.isArray(j.cdlist) ? j.cdlist[0] : null
|
|
165
|
+
if (!cd || !Array.isArray(cd.songlist)) throw httpError(`获取 QQ 音乐「我喜欢」歌曲失败(${describe(j)})`, 502)
|
|
166
|
+
return cd.songlist
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function normalize(raw) {
|
|
170
|
+
const tracks = []
|
|
171
|
+
for (const s of raw) {
|
|
172
|
+
if (!s) continue
|
|
173
|
+
const platformId = s.mid || (s.id != null ? String(s.id) : '')
|
|
174
|
+
const title = cleanText(s.name || s.title, 200)
|
|
175
|
+
if (!platformId || !title) continue
|
|
176
|
+
tracks.push({
|
|
177
|
+
platformId,
|
|
178
|
+
title,
|
|
179
|
+
artist: (Array.isArray(s.singer) ? s.singer : [])
|
|
180
|
+
.map((x) => cleanText(x && x.name, 80))
|
|
181
|
+
.filter(Boolean)
|
|
182
|
+
.join(' / '),
|
|
183
|
+
album: cleanText((s.album && (s.album.name || s.album.title)) || s.albumname, 120) || null,
|
|
184
|
+
durationMs: s.interval ? Number(s.interval) * 1000 : null,
|
|
185
|
+
likedAt: null,
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
return tracks
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** 校验 Cookie 并返回账号摘要(顺带探测「我喜欢」歌单) */
|
|
192
|
+
async function probe(authInput) {
|
|
193
|
+
const a = auth(authInput)
|
|
194
|
+
const dir = await likedDir(a)
|
|
195
|
+
return { uin: a.musicid, nickname: dir.nickname, likedDir: { tid: dir.tid, name: dir.name, songCount: dir.songCount }, cookie: a.cookie }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** 归一化后的喜欢列表:[{ platformId, title, artist, album, durationMs, likedAt }] */
|
|
199
|
+
async function likedTracks(authInput) {
|
|
200
|
+
const a = auth(authInput)
|
|
201
|
+
const dir = await likedDir(a)
|
|
202
|
+
let raw
|
|
203
|
+
try {
|
|
204
|
+
raw = await songsViaMusicu(a, dir.tid)
|
|
205
|
+
} catch (err) {
|
|
206
|
+
if (err && err.status === 401) throw err
|
|
207
|
+
raw = await songsViaLegacy(a, dir.tid)
|
|
208
|
+
}
|
|
209
|
+
return { dir, tracks: normalize(raw) }
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return { probe, likedTracks, parseCookie: parseQQCookie }
|
|
213
|
+
}
|
package/host/reco/index.js
CHANGED
|
@@ -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}
|
|
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:
|
|
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:
|
|
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
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
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
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
const
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
const
|
|
579
|
-
|
|
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/host/routes.js
CHANGED
|
@@ -4,15 +4,21 @@
|
|
|
4
4
|
* GET/POST exact /dsh-music/api/playback 播放状态读取/上报(S1 可选,S3 历史用)
|
|
5
5
|
* GET/HEAD prefix /dsh-music/audio/<id> Range 音频流
|
|
6
6
|
* GET/HEAD prefix /dsh-music/cover/<id> 内嵌封面
|
|
7
|
+
* GET/HEAD exact /dsh-music/icon.png 插件图标(设置页首启 Logo,读包内 icon.png)
|
|
7
8
|
* 安全:id 只经内存索引解析为路径,绝不拼接用户输入; realpath 必须落在曲库根内。
|
|
8
9
|
* 非 2xx 一律 JSON {error:"中文原因"}。 */
|
|
9
10
|
import { readFile, writeFile, realpath } from 'node:fs/promises'
|
|
10
11
|
import { sep } from 'node:path'
|
|
12
|
+
import { fileURLToPath } from 'node:url'
|
|
11
13
|
import { serveRangeFile } from './media-core.js'
|
|
12
14
|
|
|
13
15
|
const ID_RE = /^[a-f0-9]{16}$/
|
|
14
16
|
const AUDIO_PREFIX = '/dsh-music/audio/'
|
|
15
17
|
const COVER_PREFIX = '/dsh-music/cover/'
|
|
18
|
+
const ICON_PATH = '/dsh-music/icon.png'
|
|
19
|
+
/* routes.js 位于 bundle/host/,图标在 bundle/icon.png(package.json 的 ./icon 导出) */
|
|
20
|
+
const ICON_FILE = fileURLToPath(new URL('../icon.png', import.meta.url))
|
|
21
|
+
let iconBuffer = null
|
|
16
22
|
|
|
17
23
|
function sendJson(res, status, value) {
|
|
18
24
|
const body = JSON.stringify(value)
|
|
@@ -117,6 +123,25 @@ async function serveCover(req, res, library, storage, warn) {
|
|
|
117
123
|
res.end(req.method === 'HEAD' ? undefined : buf)
|
|
118
124
|
}
|
|
119
125
|
|
|
126
|
+
/** 插件图标:包内 icon.png 读一次后常驻内存;缺失时 404(客户端会退回内嵌 Logo)。 */
|
|
127
|
+
async function serveIcon(req, res) {
|
|
128
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return fail(res, 405, '方法不允许')
|
|
129
|
+
if (!iconBuffer) {
|
|
130
|
+
try {
|
|
131
|
+
iconBuffer = await readFile(ICON_FILE)
|
|
132
|
+
} catch {
|
|
133
|
+
iconBuffer = null
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!iconBuffer || iconBuffer.length === 0) return fail(res, 404, '插件图标不存在')
|
|
137
|
+
res.writeHead(200, {
|
|
138
|
+
'Content-Type': 'image/png',
|
|
139
|
+
'Content-Length': iconBuffer.length,
|
|
140
|
+
'Cache-Control': 'private, max-age=86400',
|
|
141
|
+
})
|
|
142
|
+
res.end(req.method === 'HEAD' ? undefined : iconBuffer)
|
|
143
|
+
}
|
|
144
|
+
|
|
120
145
|
export function registerRoutes(webServer, { library, playback, storage, logger }) {
|
|
121
146
|
const warn = (msg) => logger?.warn?.(msg)
|
|
122
147
|
const disposers = []
|
|
@@ -218,5 +243,13 @@ export function registerRoutes(webServer, { library, playback, storage, logger }
|
|
|
218
243
|
}),
|
|
219
244
|
)
|
|
220
245
|
|
|
246
|
+
disposers.push(
|
|
247
|
+
webServer.register({
|
|
248
|
+
kind: 'exact',
|
|
249
|
+
path: ICON_PATH,
|
|
250
|
+
handler: (req, res) => serveIcon(req, res),
|
|
251
|
+
}),
|
|
252
|
+
)
|
|
253
|
+
|
|
221
254
|
return disposers
|
|
222
255
|
}
|