@vicyangorg/dsh-music 0.6.0 → 0.8.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 +13 -8
- package/client/index.js +2650 -641
- 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/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/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
|
}
|
|
@@ -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
|
-
|
|
246
|
-
|
|
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: '同步可用性探测内部错误' })
|