@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.
@@ -0,0 +1,190 @@
1
+ /** 十三期:导入曲目的音源后台扫描。
2
+ * 导入只标 ♥(不下载)。这里在后台逐首用 MusicBrainz 搜(复用 search.js:命中即核实 + 留档),
3
+ * 把最佳已核实候选写进 likes.json 条目的 source 字段:
4
+ * source: { status: 'found' | 'none', checkedAt, query, hit: { artist, title, album, durationMs, verification } }
5
+ * 前端据此把行尾「入库」换成"可入库"样式;点歌 / 点入库直接用 hit,不再当场搜索(也就不会"没找到")。
6
+ * 约束:串行、跟随 reco/mb.js 的全局限速(≤1 req/s);found 不再扫;none 7 天内不重扫(可 force)。
7
+ * 评分:歌名归一后完全一致 ≫ 去括号/feat 后一致 ≫ 包含;歌手覆盖加分;MusicBrainz score 微调。 */
8
+ import { normalizeZh } from './t2s.js'
9
+ import { T2S_EXTRA } from './t2s-extra.js'
10
+
11
+ const CJK = /[\u3400-\u9fff\uf900-\ufaff]/g
12
+
13
+ const NONE_TTL_MS = 7 * 24 * 3600 * 1000
14
+ const GAP_MS = 400
15
+ const MAX_QUEUE = 5000
16
+
17
+ const PUNCT = /[\s·・,,、;;&+!-/:-@[-`{-~\u2000-\u206f\u3000-\u303f\uff00-\uffef\u2014\u2026()()「」『』【】《》〈〉“”‘’]/g
18
+
19
+ /** 比较用归一:简繁 → 小写 → 去空白与标点。 */
20
+ export function normText(value) {
21
+ return normalizeZh(String(value ?? ''))
22
+ .replace(CJK, (c) => T2S_EXTRA[c] || c)
23
+ .toLowerCase()
24
+ .replace(PUNCT, '')
25
+ }
26
+
27
+ /** 去掉括号补充、feat./ft. 尾巴,用于第二次匹配与兜底查询。 */
28
+ export function cleanTitle(value) {
29
+ return String(value ?? '')
30
+ .replace(/[((【[][^))】\]]*[))】\]]/g, ' ')
31
+ .replace(/\b(?:feat|ft|featuring|with)\b.*$/i, ' ')
32
+ .replace(/[!-/:-@[-`{-~\u2014\u2026·、,。!?;:""''…~]/g, ' ')
33
+ .replace(/\s+/g, ' ')
34
+ .trim()
35
+ }
36
+
37
+ function artistsOf(artist) {
38
+ return String(artist ?? '').split(/\s*(?:\/|、|,|,|;|;|&|\+|feat\.?|ft\.?)\s*/i).map((a) => normText(a)).filter(Boolean)
39
+ }
40
+
41
+ /** 匹配规则版本:改了评分就 +1,旧的 found 结果会在下一轮后台扫描里自动重扫(避免错配一直留着)。 */
42
+ export const SCAN_VERSION = 2
43
+ const UNKNOWN_ARTIST = /^\s*(未知歌手|未知|unknown( artist)?|artist|群星|暂无|无|-)?\s*$/i
44
+
45
+ /** 从联网候选里挑最像的一首;歌名对不上、或歌手一个都对不上(翻唱 / 同名歌)就不要。 */
46
+ export function pickHit(item, remote = []) {
47
+ const wantT = normText(item.title)
48
+ const wantC = normText(cleanTitle(item.title))
49
+ const wantA = artistsOf(item.artist)
50
+ const unknownArtist = wantA.length === 0 || UNKNOWN_ARTIST.test(String(item.artist ?? ''))
51
+ const near = (a, b) => a && b && a.length >= b.length * 0.8 && b.length >= a.length * 0.8
52
+ let best = null
53
+ for (const x of remote) {
54
+ if (!x || x.kind === 'artist' || !x.verification || !x.title) continue
55
+ const xt = normText(x.title)
56
+ let score = 0
57
+ if (xt === wantT) score += 30
58
+ else if (wantC && normText(cleanTitle(x.title)) === wantC) score += 24
59
+ else if (near(xt, wantT) && (xt.includes(wantT) || wantT.includes(xt))) score += 10
60
+ else continue
61
+ const xa = normText(x.artist)
62
+ let cover = 0
63
+ for (const a of wantA) if (a && xa.includes(a)) cover++
64
+ if (!unknownArtist && cover === 0) continue
65
+ score += unknownArtist ? 1 : cover * 6 + (cover === wantA.length ? 2 : 0)
66
+ const mbScore = Number((String((x.verification.note || '')).match(/score=(\d+)/) || [])[1])
67
+ if (Number.isFinite(mbScore)) score += Math.min(3, Math.floor(mbScore / 30))
68
+ if (!best || score > best.score) best = { x, score }
69
+ }
70
+ return best ? best.x : null
71
+ }
72
+
73
+ /** 只保留入库需要的字段(hit 原样交给下载管线的 validate:artist/title + verification)。 */
74
+ export function sanitizeHit(hit) {
75
+ if (!hit) return null
76
+ return {
77
+ kind: 'song',
78
+ id: hit.id || null,
79
+ artist: hit.artist,
80
+ title: hit.title,
81
+ album: hit.album || null,
82
+ durationMs: Number.isFinite(hit.durationMs) ? hit.durationMs : null,
83
+ source: hit.source || 'musicbrainz',
84
+ verification: hit.verification,
85
+ }
86
+ }
87
+
88
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
89
+
90
+ export function createSourceScan({ likes, search, logger, now = () => Date.now() }) {
91
+ const warn = (msg) => logger?.warn?.(msg)
92
+ const queue = []
93
+ const queued = new Set()
94
+ const state = { running: false, pending: 0, done: 0, found: 0, error: null, startedAt: null, finishedAt: null }
95
+ let disposed = false
96
+
97
+ function status() {
98
+ return { ...state, pending: queue.length }
99
+ }
100
+
101
+ /** 把 key 排进扫描队列(去重;超过上限的先丢弃,下一轮 scheduleMissing 会补上)。 */
102
+ function schedule(keys) {
103
+ if (disposed) return 0
104
+ for (const key of Array.isArray(keys) ? keys : []) {
105
+ if (queued.has(key) || queue.length >= MAX_QUEUE) continue
106
+ queued.add(key)
107
+ queue.push(key)
108
+ }
109
+ state.pending = queue.length
110
+ pump()
111
+ return queue.length
112
+ }
113
+
114
+ /** 所有还没入库的喜欢条目(found 的由 scanKey 跳过;none 的按 TTL 跳过)。 */
115
+ async function scheduleMissing({ force = false } = {}) {
116
+ const keys = await likes.missingKeys()
117
+ if (force) state.force = true
118
+ return schedule(keys)
119
+ }
120
+
121
+ async function scanKey(key) {
122
+ const item = await likes.get(key)
123
+ if (!item) return true
124
+ if (await likes.inLibrary(key)) return true
125
+ const prev = item.source
126
+ if (prev && prev.status === 'found' && prev.hit && prev.v === SCAN_VERSION) return true
127
+ if (!state.force && prev && prev.status === 'none' && now() - (Number(prev.checkedAt) || 0) < NONE_TTL_MS) return true
128
+ const queries = [...new Set([`${item.artist || ''} ${item.title || ''}`.trim(), item.title, cleanTitle(item.title)].filter((q) => q && q.length >= 2))]
129
+ let hit = null
130
+ let used = null
131
+ for (const q of queries) {
132
+ let res
133
+ try {
134
+ res = await search.search(q, 'song')
135
+ } catch (err) {
136
+ // 联网失败:本轮停摆,key 回到队首,下次 schedule 再来
137
+ state.error = err.message
138
+ queue.unshift(key)
139
+ queued.add(key)
140
+ return false
141
+ }
142
+ hit = pickHit(item, (res && res.remote) || [])
143
+ if (hit) { used = q; break }
144
+ if (disposed) return false
145
+ }
146
+ if (disposed) return false
147
+ await likes.setSource(key, { status: hit ? 'found' : 'none', checkedAt: now(), query: used, hit: sanitizeHit(hit), v: SCAN_VERSION })
148
+ state.done += 1
149
+ if (hit) state.found += 1
150
+ return true
151
+ }
152
+
153
+ let pumping = null
154
+ function pump() {
155
+ if (pumping || disposed) return pumping
156
+ if (!queue.length) return null
157
+ pumping = (async () => {
158
+ state.running = true
159
+ state.startedAt = now()
160
+ state.finishedAt = null
161
+ try {
162
+ while (queue.length && !disposed) {
163
+ const key = queue.shift()
164
+ queued.delete(key)
165
+ const ok = await scanKey(key)
166
+ if (!ok) break
167
+ await sleep(GAP_MS)
168
+ }
169
+ } catch (err) {
170
+ warn(`dsh-music: 音源后台扫描出错: ${err.message}`)
171
+ state.error = err.message
172
+ } finally {
173
+ state.running = false
174
+ state.finishedAt = now()
175
+ state.pending = queue.length
176
+ state.force = false
177
+ pumping = null
178
+ }
179
+ })()
180
+ return pumping
181
+ }
182
+
183
+ function dispose() {
184
+ disposed = true
185
+ queue.length = 0
186
+ queued.clear()
187
+ }
188
+
189
+ return { schedule, scheduleMissing, status, scanKey, dispose }
190
+ }
package/host/sync.js CHANGED
@@ -7,9 +7,11 @@
7
7
  import { spawn } from 'node:child_process'
8
8
  import { access, constants } from 'node:fs/promises'
9
9
  import { delimiter, join } from 'node:path'
10
+ import { homedir } from 'node:os'
10
11
 
11
12
  const SYNC_TIMEOUT_MS = 30 * 60 * 1000
12
13
  const MAX_LINES = 300
14
+ const TOKEN_FILE = join(homedir(), '.config', 'spotify-sync', 'refresh_token')
13
15
  const OPTIONAL_HINT = '未检测到 spotify-sync CLI。Spotify 同步是可选功能:安装 spotify-sync 后即可启用(或在本插件 config 中设置 syncCommand / syncScriptPath),不影响本地曲库、搜索、试听与推荐。'
14
16
 
15
17
  /** 解析 CLI 输出:云端/新增/移除 行、逐曲结果行、「完成 {...}」汇总(Python dict repr)。 */
@@ -72,25 +74,35 @@ export function createSync({ library, config = {}, logger }) {
72
74
 
73
75
  /** 探测 CLI 可用性(不跑同步):config.syncCommand → PATH 的 spotify-sync →
74
76
  * config.syncScriptPath(python3 直跑技能脚本)。结果进程内缓存,probe() 可强制重探。 */
77
+ /** spotify-sync 自己保管的登录凭据是否已就位:只做「文件存在」检查,绝不读取内容(红线)。 */
78
+ async function authorized() {
79
+ try {
80
+ await access(config.spotifyTokenPath || TOKEN_FILE, constants.R_OK)
81
+ return true
82
+ } catch {
83
+ return false
84
+ }
85
+ }
86
+
75
87
  async function availability() {
76
88
  if (cached) return cached
77
89
  const cmd = typeof config.syncCommand === 'string' && config.syncCommand ? config.syncCommand : null
78
90
  if (cmd) {
79
91
  if (await executable(cmd)) {
80
- cached = { available: true, mode: 'cli', command: cmd, message: null }
92
+ cached = { available: true, mode: 'cli', command: cmd, message: null, authorized: await authorized() }
81
93
  return cached
82
94
  }
83
95
  warn(`dsh-music: 配置的 syncCommand 不可执行(${cmd}),继续探测 PATH`)
84
96
  }
85
97
  const found = await findOnPath('spotify-sync')
86
98
  if (found) {
87
- cached = { available: true, mode: 'cli', command: found, message: null }
99
+ cached = { available: true, mode: 'cli', command: found, message: null, authorized: await authorized() }
88
100
  return cached
89
101
  }
90
102
  const script = typeof config.syncScriptPath === 'string' && config.syncScriptPath ? config.syncScriptPath : null
91
103
  if (script && await executable(script)) {
92
104
  const python = config.pythonPath || (await findOnPath('python3')) || '/usr/bin/python3'
93
- cached = { available: true, mode: 'script', command: python, script, message: null }
105
+ cached = { available: true, mode: 'script', command: python, script, message: null, authorized: await authorized() }
94
106
  return cached
95
107
  }
96
108
  cached = { available: false, mode: null, command: null, message: OPTIONAL_HINT }
@@ -242,8 +254,9 @@ export function registerSyncRoutes(webServer, { sync, logger }) {
242
254
  handler: async (req, res) => {
243
255
  if (req.method !== 'GET') return sendJson(res, 405, { error: '方法不允许' })
244
256
  try {
245
- const av = await sync.availability()
246
- return sendJson(res, 200, { available: av.available, hint: av.available ? null : av.message })
257
+ /* ?refresh=1:用户装好 CLI / 完成授权后点「重新检测」→ 重探(仍不执行 CLI,只查文件) */
258
+ const av = /[?&]refresh=1/.test(String(req.url || '')) ? await sync.probe() : await sync.availability()
259
+ return sendJson(res, 200, { available: av.available, hint: av.available ? null : av.message, authorized: av.authorized == null ? null : !!av.authorized })
247
260
  } catch (err) {
248
261
  warn(`dsh-music: 同步可用性探测错误: ${err.message}`)
249
262
  return sendJson(res, 500, { error: '同步可用性探测内部错误' })