feat: Lyrics
This commit is contained in:
1 parent
6ed3e169e4
commit
82b1fa0d47
17 files changed
+3863
-283
No files matched your search
+556
@@ -0,0 +1,556 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* LRC 解析 / 过滤 / 时间轴构建。
|
||||
*
|
||||
* 纯函数模块,不依赖 express / fs,方便单元测试,也方便服务端和 API 复用。
|
||||
*/
|
||||
|
||||
const MAX_SOURCE_CHARS = 2_000_000;
|
||||
const MAX_LINES = 5000;
|
||||
|
||||
/** 默认用于过滤版权 / 制作信息行的关键词(命中行首附近即视为制作信息) */
|
||||
const DEFAULT_CREDIT_KEYWORDS = [
|
||||
'作词', '作曲', '编曲', '词曲', '词:', '曲:', '制作人', '制作', '出品', '监制',
|
||||
'录音', '混音', '母带', '发行', '版权', '策划', '统筹', '艺术总监', '和声',
|
||||
'吉他', '贝斯', '鼓手', '弦乐', '录音师', '混音师', '母带师', '演唱', '原唱',
|
||||
'歌词制作', '歌词编辑', '翻译', '校对', 'lrc制作', 'lrc编辑',
|
||||
'lyrics by', 'composed by', 'written by', 'arranged by', 'produced by',
|
||||
'mixed by', 'mastered by', 'copyright', 'all rights reserved', 'op:', 'sp:',
|
||||
'℗', '©',
|
||||
];
|
||||
|
||||
const LRC_POSITIONS = ['top', 'center', 'bottom'];
|
||||
const LRC_ALIGNS = ['left', 'center', 'right'];
|
||||
const LRC_ANIMATIONS = ['none', 'fade', 'slide', 'zoom', 'blur', 'bounce', 'custom'];
|
||||
|
||||
const DEFAULT_LRC_FILTERS = {
|
||||
dropCreditLines: true,
|
||||
// 是否丢弃没有时间戳的行(LRC 里通常是标题、版权、备注)
|
||||
dropUntimed: true,
|
||||
creditKeywords: DEFAULT_CREDIT_KEYWORDS,
|
||||
};
|
||||
|
||||
const DEFAULT_LRC_STYLE = {
|
||||
position: 'bottom',
|
||||
align: 'center',
|
||||
fontFamily: "'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', system-ui, sans-serif",
|
||||
fontSize: 42,
|
||||
fontWeight: 700,
|
||||
color: '#ffffff',
|
||||
letterSpacing: 1,
|
||||
lineHeight: 1.35,
|
||||
background: 'rgba(0, 0, 0, 0.55)',
|
||||
backgroundEnabled: true,
|
||||
paddingX: 28,
|
||||
paddingY: 12,
|
||||
borderRadius: 12,
|
||||
maxWidthPercent: 86,
|
||||
textShadow: '0 2px 12px rgba(0, 0, 0, 0.85)',
|
||||
textShadowEnabled: true,
|
||||
animation: 'fade',
|
||||
// 自定义 CSS / 自定义动画:作用于 .lrc-layer / .lrc-box / .lrc-text / .lrc-word
|
||||
customCss: '',
|
||||
showNextLine: true,
|
||||
nextLineColor: 'rgba(255, 255, 255, 0.55)',
|
||||
nextLineScale: 0.68,
|
||||
bottomOffsetVh: 7,
|
||||
// 逐字:仅对含增强型 <mm:ss.xx> 标签的行生效
|
||||
karaoke: true,
|
||||
karaokePendingColor: 'rgba(255, 255, 255, 0.45)',
|
||||
};
|
||||
|
||||
const DEFAULT_LRC_TIMING = {
|
||||
offsetMs: 0,
|
||||
tailMs: 4000,
|
||||
};
|
||||
|
||||
// ── 解析 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
function normalizeSource(source) {
|
||||
return String(source == null ? '' : source)
|
||||
.slice(0, MAX_SOURCE_CHARS)
|
||||
.replace(/^\uFEFF/, '')
|
||||
.replace(/\r\n?/g, '\n');
|
||||
}
|
||||
|
||||
/** 把 "mm:ss.xx" / "mm:ss:xx" / "mm:ss" 解析成秒,失败返回 null */
|
||||
function parseTimestamp(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const m = /^(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?$/.exec(text);
|
||||
if (!m) return null;
|
||||
const minutes = Number(m[1]);
|
||||
const seconds = Number(m[2]);
|
||||
if (!Number.isFinite(minutes) || !Number.isFinite(seconds) || seconds > 59) return null;
|
||||
let fraction = 0;
|
||||
if (m[3] !== undefined) {
|
||||
fraction = Number(m[3]) / Math.pow(10, m[3].length);
|
||||
}
|
||||
return minutes * 60 + seconds + fraction;
|
||||
}
|
||||
|
||||
function cleanText(text) {
|
||||
return text
|
||||
.replace(/\u00a0/g, ' ')
|
||||
.replace(/[ \t]+$/g, '')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析增强型逐字标签:<mm:ss.xx>文字
|
||||
* 返回纯文本 + 逐字片段(片段 time 为 LRC 原始绝对时间,单位秒)。
|
||||
* 没有增强标签时 segments 为 null。
|
||||
*/
|
||||
function extractEnhancedText(rest, fallbackTime) {
|
||||
const tagRe = /<(\d{1,3}:\d{1,2}(?:[.:]\d{1,3})?)>/g;
|
||||
const matches = [];
|
||||
let match;
|
||||
while ((match = tagRe.exec(rest)) !== null) {
|
||||
const time = parseTimestamp(match[1]);
|
||||
if (time !== null) matches.push({ start: match.index, end: tagRe.lastIndex, time });
|
||||
}
|
||||
|
||||
if (!matches.length) {
|
||||
return { text: cleanText(rest), segments: null };
|
||||
}
|
||||
|
||||
const segments = [];
|
||||
let cursor = 0;
|
||||
let currentTime = Number.isFinite(fallbackTime) ? fallbackTime : 0;
|
||||
for (const tag of matches) {
|
||||
const chunk = rest.slice(cursor, tag.start).replace(/\u00a0/g, ' ');
|
||||
if (chunk) segments.push({ time: currentTime, text: chunk });
|
||||
currentTime = tag.time;
|
||||
cursor = tag.end;
|
||||
}
|
||||
const tail = rest.slice(cursor).replace(/\u00a0/g, ' ');
|
||||
if (tail) segments.push({ time: currentTime, text: tail });
|
||||
|
||||
// 去掉整行首尾空白,但保留词与词之间的空格
|
||||
if (segments.length) {
|
||||
segments[0] = { ...segments[0], text: segments[0].text.replace(/^\s+/, '') };
|
||||
const last = segments.length - 1;
|
||||
segments[last] = { ...segments[last], text: segments[last].text.replace(/\s+$/, '') };
|
||||
}
|
||||
|
||||
const cleaned = segments.filter((segment) => segment.text);
|
||||
const text = cleanText(cleaned.map((segment) => segment.text).join(''));
|
||||
return {
|
||||
text,
|
||||
// 只有多段逐字时间轴才有意义
|
||||
segments: cleaned.length >= 2 ? cleaned : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 LRC 文本。
|
||||
* @param {string} source
|
||||
* @returns {{
|
||||
* meta: Record<string,string>, metaOffsetMs: number,
|
||||
* lines: Array<any>, lyricEntries: Array<any>,
|
||||
* warnings: string[], sourceLineCount: number
|
||||
* }}
|
||||
*/
|
||||
function parseLrc(source) {
|
||||
const text = normalizeSource(source);
|
||||
const rawLines = text.split('\n');
|
||||
const lines = [];
|
||||
const lyricEntries = [];
|
||||
const meta = {};
|
||||
const warnings = [];
|
||||
let consumedLines = 0;
|
||||
|
||||
for (let i = 0; i < rawLines.length; i += 1) {
|
||||
if (consumedLines >= MAX_LINES) {
|
||||
warnings.push(`歌词行数超过 ${MAX_LINES} 行,已截断`);
|
||||
break;
|
||||
}
|
||||
consumedLines += 1;
|
||||
|
||||
const raw = rawLines[i];
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) {
|
||||
lines.push({ line: i + 1, raw, text: '', times: [], time: null, kind: 'blank' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const times = [];
|
||||
const inlineMeta = [];
|
||||
let rest = trimmed;
|
||||
|
||||
// 只解析行首连续的 [xx] 标签
|
||||
const leading = /^((?:\[[^\[\]]*\])+)([\s\S]*)$/.exec(trimmed);
|
||||
if (leading) {
|
||||
rest = leading[2];
|
||||
const tagRe = /\[([^\[\]]*)\]/g;
|
||||
let tagMatch;
|
||||
while ((tagMatch = tagRe.exec(leading[1])) !== null) {
|
||||
const inner = tagMatch[1].trim();
|
||||
const seconds = parseTimestamp(inner);
|
||||
if (seconds !== null) {
|
||||
times.push(seconds);
|
||||
continue;
|
||||
}
|
||||
const metaMatch = /^([a-zA-Z][a-zA-Z0-9_#-]*)\s*:\s*([\s\S]*)$/.exec(inner);
|
||||
if (metaMatch) {
|
||||
inlineMeta.push({ key: metaMatch[1].toLowerCase(), value: metaMatch[2].trim() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const enhanced = extractEnhancedText(rest, times.length ? Math.min(...times) : 0);
|
||||
const lyricText = enhanced.text;
|
||||
|
||||
for (const tag of inlineMeta) {
|
||||
// 同名标签保留第一次出现的值(更符合直觉)
|
||||
if (!(tag.key in meta)) meta[tag.key] = tag.value;
|
||||
}
|
||||
|
||||
if (times.length === 0) {
|
||||
if (lyricText) {
|
||||
lines.push({
|
||||
line: i + 1, raw, text: lyricText, times: [], time: null,
|
||||
kind: inlineMeta.length ? 'meta' : 'untimed',
|
||||
});
|
||||
} else if (inlineMeta.length) {
|
||||
lines.push({
|
||||
line: i + 1, raw, text: '', times: [], time: null,
|
||||
kind: 'meta', meta: inlineMeta,
|
||||
});
|
||||
} else {
|
||||
lines.push({ line: i + 1, raw, text: '', times: [], time: null, kind: 'blank' });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const timesSorted = times.slice().sort((a, b) => a - b);
|
||||
// 增强型逐字时间轴只对单时间戳歌词有效;一行多时间戳(副歌复用)无法对应,退回整句
|
||||
const entrySegments = timesSorted.length === 1 ? enhanced.segments : null;
|
||||
lines.push({
|
||||
line: i + 1, raw, text: lyricText, times: timesSorted, time: timesSorted[0],
|
||||
kind: lyricText ? 'lyric' : 'blank', segments: entrySegments,
|
||||
});
|
||||
|
||||
if (lyricText) {
|
||||
for (const seconds of timesSorted) {
|
||||
lyricEntries.push({
|
||||
line: i + 1,
|
||||
time: seconds,
|
||||
text: lyricText,
|
||||
segments: entrySegments,
|
||||
raw,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lyricEntries.sort((a, b) => (a.time - b.time) || (a.line - b.line));
|
||||
|
||||
if (!lyricEntries.length) {
|
||||
warnings.push('没有找到带时间戳的歌词行,请确认 LRC 格式是否正确');
|
||||
}
|
||||
|
||||
let metaOffsetMs = 0;
|
||||
if (meta.offset !== undefined) {
|
||||
const parsedOffset = Number(String(meta.offset).replace(/[^\d.+-]/g, ''));
|
||||
if (Number.isFinite(parsedOffset)) metaOffsetMs = Math.round(parsedOffset);
|
||||
}
|
||||
|
||||
return {
|
||||
meta,
|
||||
metaOffsetMs,
|
||||
lines,
|
||||
lyricEntries,
|
||||
warnings,
|
||||
sourceLineCount: consumedLines,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 过滤 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
function normalizeKeywordList(input) {
|
||||
if (!Array.isArray(input)) return DEFAULT_CREDIT_KEYWORDS.slice();
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
for (const item of input) {
|
||||
const kw = String(item == null ? '' : item).trim();
|
||||
if (!kw) continue;
|
||||
const lower = kw.toLowerCase();
|
||||
if (seen.has(lower)) continue;
|
||||
seen.add(lower);
|
||||
result.push(kw.slice(0, 40));
|
||||
if (result.length >= 120) break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一行歌词是否是版权 / 制作信息。
|
||||
* 规则:出现 © / ℗,或配置的关键词出现在行首附近(允许少量标点前缀)。
|
||||
*/
|
||||
function isCreditLine(text, keywords) {
|
||||
const value = String(text == null ? '' : text).trim();
|
||||
if (!value) return false;
|
||||
if (/[©℗]/.test(value)) return true;
|
||||
|
||||
const lower = value.toLowerCase();
|
||||
const list = Array.isArray(keywords) ? keywords : DEFAULT_CREDIT_KEYWORDS;
|
||||
for (const rawKeyword of list) {
|
||||
const keyword = String(rawKeyword == null ? '' : rawKeyword).trim().toLowerCase();
|
||||
if (!keyword) continue;
|
||||
const idx = lower.indexOf(keyword);
|
||||
if (idx === -1) continue;
|
||||
if (idx <= 6) return true;
|
||||
// 括号中的英文制作信息,例如 "Song (Prod. by XXX)"
|
||||
if (/^[a-z]/.test(keyword) && idx <= 40) {
|
||||
const prefix = lower.slice(Math.max(0, idx - 2), idx);
|
||||
if (/[((\[【]/.test(prefix)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function normalizeRange(range) {
|
||||
const input = range && typeof range === 'object' ? range : {};
|
||||
const start = Number.isFinite(Number(input.startIndex)) ? Math.max(0, Math.floor(Number(input.startIndex))) : 0;
|
||||
let end = null;
|
||||
if (input.endIndex !== null && input.endIndex !== undefined && input.endIndex !== '') {
|
||||
const parsed = Number(input.endIndex);
|
||||
if (Number.isFinite(parsed)) end = Math.max(0, Math.floor(parsed));
|
||||
}
|
||||
if (end !== null && end < start) end = start;
|
||||
return { startIndex: start, endIndex: end };
|
||||
}
|
||||
|
||||
function normalizeFilters(filters) {
|
||||
const input = filters && typeof filters === 'object' ? filters : {};
|
||||
return {
|
||||
dropCreditLines: input.dropCreditLines !== false,
|
||||
dropUntimed: input.dropUntimed !== false,
|
||||
creditKeywords: normalizeKeywordList(
|
||||
Array.isArray(input.creditKeywords) ? input.creditKeywords : DEFAULT_LRC_FILTERS.creditKeywords
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据过滤条件 + 范围构建最终字幕时间轴。
|
||||
* 时间轴以「第一个入选句子」为 0 点,因此打点时第一句会立即出现(自动偏移)。
|
||||
*/
|
||||
function buildTimeline(parsed, options = {}) {
|
||||
const filters = normalizeFilters(options.filters);
|
||||
const range = normalizeRange(options.range);
|
||||
const offsetMs = clampNumber(options.offsetMs, -60000, 60000, 0);
|
||||
const tailMs = clampNumber(options.tailMs, 0, 60000, DEFAULT_LRC_TIMING.tailMs);
|
||||
const metaOffsetMs = Number.isFinite(parsed.metaOffsetMs) ? parsed.metaOffsetMs : 0;
|
||||
|
||||
const keptCandidates = [];
|
||||
const excluded = [];
|
||||
const stats = {
|
||||
sourceLines: parsed.sourceLineCount || parsed.lines.length,
|
||||
timedLyricLines: parsed.lyricEntries.length,
|
||||
excludedCredit: 0,
|
||||
excludedUntimed: 0,
|
||||
keptLyricLines: 0,
|
||||
cueCount: 0,
|
||||
};
|
||||
|
||||
for (const entry of parsed.lyricEntries) {
|
||||
if (filters.dropCreditLines && isCreditLine(entry.text, filters.creditKeywords)) {
|
||||
stats.excludedCredit += 1;
|
||||
excluded.push({ time: entry.time, text: entry.text, line: entry.line, reason: '版权/制作信息' });
|
||||
continue;
|
||||
}
|
||||
keptCandidates.push(entry);
|
||||
}
|
||||
|
||||
if (filters.dropUntimed) {
|
||||
for (const line of parsed.lines) {
|
||||
if (line.kind !== 'untimed') continue;
|
||||
stats.excludedUntimed += 1;
|
||||
excluded.push({ time: null, text: line.text, line: line.line, reason: '无时间戳' });
|
||||
}
|
||||
}
|
||||
|
||||
stats.keptLyricLines = keptCandidates.length;
|
||||
const maxIndex = Math.max(0, keptCandidates.length - 1);
|
||||
const startIndex = keptCandidates.length ? Math.min(range.startIndex, maxIndex) : 0;
|
||||
const endIndex = keptCandidates.length
|
||||
? Math.min(range.endIndex === null ? maxIndex : range.endIndex, maxIndex)
|
||||
: 0;
|
||||
const selected = keptCandidates.slice(startIndex, endIndex + 1);
|
||||
|
||||
const shiftMs = offsetMs - metaOffsetMs;
|
||||
const firstTime = selected.length ? selected[0].time : 0;
|
||||
const cueMap = new Map();
|
||||
|
||||
for (const entry of selected) {
|
||||
const rawT = Math.round((entry.time - firstTime) * 1000) + shiftMs;
|
||||
const t = Math.max(0, rawT);
|
||||
const text = entry.text.trim();
|
||||
if (!text) continue;
|
||||
|
||||
let segments = null;
|
||||
if (Array.isArray(entry.segments) && entry.segments.length >= 2) {
|
||||
segments = entry.segments
|
||||
.map((segment) => ({
|
||||
at: Math.max(0, Math.round((segment.time - firstTime) * 1000) + shiftMs),
|
||||
text: segment.text,
|
||||
}))
|
||||
.filter((segment) => segment.text)
|
||||
.sort((a, b) => a.at - b.at);
|
||||
if (segments.length < 2) segments = null;
|
||||
}
|
||||
|
||||
if (cueMap.has(t)) {
|
||||
const existing = cueMap.get(t);
|
||||
existing.text = `${existing.text}\n${text}`;
|
||||
// 双语/多行合并后无法复用逐字时间轴,退回整句点亮
|
||||
existing.segments = null;
|
||||
} else {
|
||||
cueMap.set(t, {
|
||||
t,
|
||||
text,
|
||||
line: entry.line,
|
||||
sourceTimeMs: Math.round(entry.time * 1000),
|
||||
segments,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const cues = Array.from(cueMap.values()).sort((a, b) => a.t - b.t).map((cue, index) => ({
|
||||
...cue,
|
||||
index,
|
||||
}));
|
||||
|
||||
const lastCue = cues[cues.length - 1] || null;
|
||||
stats.cueCount = cues.length;
|
||||
stats.karaokeCues = cues.filter((cue) => Array.isArray(cue.segments) && cue.segments.length >= 2).length;
|
||||
|
||||
const candidates = keptCandidates.map((entry, index) => ({
|
||||
index,
|
||||
time: entry.time,
|
||||
text: entry.text,
|
||||
line: entry.line,
|
||||
inRange: index >= startIndex && index <= endIndex,
|
||||
}));
|
||||
|
||||
return {
|
||||
cues,
|
||||
candidates,
|
||||
excluded,
|
||||
stats,
|
||||
range: { startIndex, endIndex: keptCandidates.length ? endIndex : null },
|
||||
requestedRange: range,
|
||||
offsetMs,
|
||||
metaOffsetMs,
|
||||
shiftMs,
|
||||
tailMs,
|
||||
firstSourceTimeMs: selected.length ? Math.round(firstTime * 1000) : null,
|
||||
lastSourceTimeMs: lastCue ? lastCue.sourceTimeMs : null,
|
||||
totalMs: lastCue ? lastCue.t : 0,
|
||||
endMs: lastCue ? lastCue.t + tailMs : 0,
|
||||
keptCount: keptCandidates.length,
|
||||
};
|
||||
}
|
||||
|
||||
function clampNumber(value, min, max, fallback) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return fallback;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
// ── 预设校验 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function cleanString(value, maxLength) {
|
||||
if (typeof value !== 'string') return '';
|
||||
return value.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function normalizeStyle(input) {
|
||||
const src = input && typeof input === 'object' ? input : {};
|
||||
const style = { ...DEFAULT_LRC_STYLE };
|
||||
if (LRC_POSITIONS.includes(src.position)) style.position = src.position;
|
||||
if (LRC_ALIGNS.includes(src.align)) style.align = src.align;
|
||||
if (LRC_ANIMATIONS.includes(src.animation)) style.animation = src.animation;
|
||||
if (typeof src.fontFamily === 'string' && src.fontFamily.trim()) {
|
||||
style.fontFamily = cleanString(src.fontFamily, 200);
|
||||
}
|
||||
if (typeof src.color === 'string' && src.color.trim()) style.color = cleanString(src.color, 40);
|
||||
if (typeof src.background === 'string') style.background = cleanString(src.background, 80);
|
||||
if (typeof src.textShadow === 'string') style.textShadow = cleanString(src.textShadow, 160);
|
||||
if (typeof src.nextLineColor === 'string') style.nextLineColor = cleanString(src.nextLineColor, 60);
|
||||
if (typeof src.karaokePendingColor === 'string') style.karaokePendingColor = cleanString(src.karaokePendingColor, 60);
|
||||
if (typeof src.customCss === 'string') style.customCss = cleanString(src.customCss, 50_000);
|
||||
|
||||
style.fontSize = clampNumber(src.fontSize, 12, 200, style.fontSize);
|
||||
style.fontWeight = clampNumber(src.fontWeight, 100, 900, style.fontWeight);
|
||||
style.letterSpacing = clampNumber(src.letterSpacing, -10, 40, style.letterSpacing);
|
||||
style.lineHeight = clampNumber(src.lineHeight, 0.8, 3, style.lineHeight);
|
||||
style.paddingX = clampNumber(src.paddingX, 0, 200, style.paddingX);
|
||||
style.paddingY = clampNumber(src.paddingY, 0, 120, style.paddingY);
|
||||
style.borderRadius = clampNumber(src.borderRadius, 0, 100, style.borderRadius);
|
||||
style.maxWidthPercent = clampNumber(src.maxWidthPercent, 20, 100, style.maxWidthPercent);
|
||||
style.nextLineScale = clampNumber(src.nextLineScale, 0.3, 1, style.nextLineScale);
|
||||
style.bottomOffsetVh = clampNumber(src.bottomOffsetVh, 0, 45, style.bottomOffsetVh);
|
||||
style.showNextLine = src.showNextLine !== false;
|
||||
style.backgroundEnabled = src.backgroundEnabled !== false;
|
||||
style.textShadowEnabled = src.textShadowEnabled !== false;
|
||||
style.karaoke = src.karaoke !== false;
|
||||
return style;
|
||||
}
|
||||
|
||||
function normalizeLrcPreset(input) {
|
||||
const src = input && typeof input === 'object' ? input : {};
|
||||
const id = String(src.id || '').trim();
|
||||
if (!id) throw new Error('LRC 预设缺少 id');
|
||||
|
||||
const source = typeof src.source === 'string' ? cleanString(src.source, MAX_SOURCE_CHARS) : '';
|
||||
const parsed = parseLrc(source);
|
||||
const range = normalizeRange(src.range);
|
||||
const maxIndex = Math.max(0, parsed.lyricEntries.length - 1);
|
||||
if (parsed.lyricEntries.length) {
|
||||
range.startIndex = Math.min(range.startIndex, maxIndex);
|
||||
if (range.endIndex !== null) {
|
||||
range.endIndex = Math.min(Math.max(range.endIndex, range.startIndex), maxIndex);
|
||||
}
|
||||
} else {
|
||||
range.startIndex = 0;
|
||||
range.endIndex = null;
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
id,
|
||||
name: cleanString(String(src.name || ''), 120).trim() || '未命名 LRC 字幕',
|
||||
source,
|
||||
filters: normalizeFilters(src.filters),
|
||||
range,
|
||||
offsetMs: clampNumber(src.offsetMs, -60000, 60000, DEFAULT_LRC_TIMING.offsetMs),
|
||||
tailMs: clampNumber(src.tailMs, 0, 60000, DEFAULT_LRC_TIMING.tailMs),
|
||||
style: normalizeStyle(src.style),
|
||||
createdAt: src.createdAt || now,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_CREDIT_KEYWORDS,
|
||||
DEFAULT_LRC_FILTERS,
|
||||
DEFAULT_LRC_STYLE,
|
||||
DEFAULT_LRC_TIMING,
|
||||
LRC_POSITIONS,
|
||||
LRC_ALIGNS,
|
||||
LRC_ANIMATIONS,
|
||||
MAX_SOURCE_CHARS,
|
||||
parseLrc,
|
||||
parseTimestamp,
|
||||
buildTimeline,
|
||||
isCreditLine,
|
||||
normalizeFilters,
|
||||
normalizeRange,
|
||||
normalizeStyle,
|
||||
normalizeLrcPreset,
|
||||
normalizeKeywordList,
|
||||
clampNumber,
|
||||
};
|
||||
@@ -0,0 +1,91 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 外观预设 / 内容预设 / 设置的校验与规整。
|
||||
* 保持与旧版 API 字段兼容,同时对长度、枚举、类型做约束。
|
||||
*/
|
||||
|
||||
const LRC_STYLE_DEFAULTS = require('./lrc').DEFAULT_LRC_STYLE;
|
||||
|
||||
const ALIGNS = ['left', 'center', 'right'];
|
||||
|
||||
function str(value, maxLength) {
|
||||
if (typeof value !== 'string') return '';
|
||||
return value.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function idOf(input) {
|
||||
const id = String(input && input.id != null ? input.id : '').trim();
|
||||
if (!id) throw new Error('缺少 id');
|
||||
return id;
|
||||
}
|
||||
|
||||
function normalizeFieldDefs(input) {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
for (const raw of input) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const key = str(raw.key, 64).trim();
|
||||
if (!key || !/^[\w-]+$/.test(key) || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
result.push({
|
||||
key,
|
||||
label: str(raw.label, 80).trim() || key,
|
||||
defaultValue: str(raw.defaultValue, 2000),
|
||||
});
|
||||
if (result.length >= 40) break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function normalizeAppearancePreset(input) {
|
||||
const src = input && typeof input === 'object' ? input : {};
|
||||
const align = ALIGNS.includes(src.align) ? src.align : 'right';
|
||||
return {
|
||||
id: idOf(src),
|
||||
name: str(src.name, 120).trim() || '未命名外观',
|
||||
kind: 'iframe',
|
||||
align,
|
||||
themeColor: str(src.themeColor, 40),
|
||||
extraCss: str(src.extraCss, 200_000),
|
||||
fieldDefs: normalizeFieldDefs(src.fieldDefs),
|
||||
html: str(src.html, 1_000_000),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeContentPreset(input) {
|
||||
const src = input && typeof input === 'object' ? input : {};
|
||||
const fields = {};
|
||||
if (src.fields && typeof src.fields === 'object' && !Array.isArray(src.fields)) {
|
||||
let count = 0;
|
||||
for (const [key, value] of Object.entries(src.fields)) {
|
||||
if (!/^[\w-]+$/.test(key)) continue;
|
||||
fields[key] = str(typeof value === 'string' ? value : String(value == null ? '' : value), 20_000);
|
||||
count += 1;
|
||||
if (count >= 80) break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: idOf(src),
|
||||
name: str(src.name, 120).trim() || '未命名内容',
|
||||
appearancePresetId: str(src.appearancePresetId, 120),
|
||||
fields,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeSettings(input) {
|
||||
const src = input && typeof input === 'object' ? input : {};
|
||||
const duration = Number(src.autoHideDuration);
|
||||
return {
|
||||
autoHideDuration: Number.isFinite(duration) ? Math.max(0, Math.min(600_000, Math.round(duration))) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ALIGNS,
|
||||
LRC_STYLE_DEFAULTS,
|
||||
normalizeAppearancePreset,
|
||||
normalizeContentPreset,
|
||||
normalizeSettings,
|
||||
};
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 首次启动时使用的种子数据。
|
||||
*
|
||||
* 种子内容放在 seed/ 目录(HTML / LRC 用独立文件),
|
||||
* 运行时数据写入 data/,两者分离,不会把用户数据写进源码。
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { DEFAULT_CREDIT_KEYWORDS } = require('./lrc');
|
||||
const { normalizeSettings } = require('./models');
|
||||
|
||||
const SEED_DIR = path.join(__dirname, '..', 'seed');
|
||||
|
||||
function readSeedFile(name) {
|
||||
if (!name) return '';
|
||||
try {
|
||||
return fs.readFileSync(path.join(SEED_DIR, name), 'utf8');
|
||||
} catch (err) {
|
||||
console.warn(`[seed] 无法读取种子文件 ${name}: ${err.message}`);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function loadSeed() {
|
||||
let raw = {};
|
||||
try {
|
||||
raw = JSON.parse(readSeedFile('defaults.json') || '{}');
|
||||
} catch (err) {
|
||||
console.warn(`[seed] defaults.json 解析失败: ${err.message}`);
|
||||
}
|
||||
|
||||
const appearancePresets = (Array.isArray(raw.appearancePresets) ? raw.appearancePresets : []).map((preset) => ({
|
||||
...preset,
|
||||
html: readSeedFile(preset.htmlFile),
|
||||
}));
|
||||
|
||||
const contentPresets = Array.isArray(raw.contentPresets) ? raw.contentPresets : [];
|
||||
|
||||
const lrcPresets = (Array.isArray(raw.lrcPresets) ? raw.lrcPresets : []).map((preset) => ({
|
||||
...preset,
|
||||
source: readSeedFile(preset.sourceFile),
|
||||
filters: {
|
||||
dropCreditLines: true,
|
||||
dropUntimed: true,
|
||||
creditKeywords: DEFAULT_CREDIT_KEYWORDS,
|
||||
...(preset.filters || {}),
|
||||
},
|
||||
}));
|
||||
|
||||
return {
|
||||
appearancePresets,
|
||||
contentPresets,
|
||||
lrcPresets,
|
||||
settings: normalizeSettings(raw.settings),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { loadSeed, SEED_DIR };
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 轻量 JSON 持久化存储。
|
||||
*
|
||||
* - 所有运行时数据都保存在 data/ 目录(可通过 DATA_DIR 环境变量覆盖),
|
||||
* 不会写死在源代码里。
|
||||
* - 写入使用「临时文件 + rename」的原子方式,避免进程中断留下半个 JSON。
|
||||
* - 文件损坏时自动备份为 *.corrupt-<时间戳>.bak 并使用种子数据重建。
|
||||
* - 每个文件带有 schemaVersion,方便以后做数据迁移。
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { randomUUID } = require('crypto');
|
||||
|
||||
const SCHEMA_VERSION = 1;
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function clone(value) {
|
||||
return JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
|
||||
function atomicWriteJson(filePath, value) {
|
||||
const dir = path.dirname(filePath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const text = JSON.stringify(value, null, 2) + '\n';
|
||||
const tmp = `${filePath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
||||
fs.writeFileSync(tmp, text, 'utf8');
|
||||
try {
|
||||
fs.renameSync(tmp, filePath);
|
||||
} catch (err) {
|
||||
try { fs.unlinkSync(tmp); } catch (_) { /* ignore */ }
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function backupCorrupt(filePath) {
|
||||
try {
|
||||
const backup = `${filePath}.corrupt-${Date.now()}.bak`;
|
||||
fs.copyFileSync(filePath, backup);
|
||||
console.error(`[store] ${path.basename(filePath)} 无法解析,已备份到 ${path.basename(backup)}`);
|
||||
} catch (err) {
|
||||
console.error(`[store] 备份损坏文件失败: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function readJsonFile(filePath) {
|
||||
const raw = fs.readFileSync(filePath, 'utf8');
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
/** 通用 JSON 文档(对象) */
|
||||
class JsonDocument {
|
||||
constructor(filePath, defaultValue) {
|
||||
this.filePath = filePath;
|
||||
this.defaultValue = clone(defaultValue);
|
||||
this.value = clone(defaultValue);
|
||||
this.loaded = false;
|
||||
this.load();
|
||||
}
|
||||
|
||||
load() {
|
||||
try {
|
||||
const parsed = readJsonFile(this.filePath);
|
||||
if (parsed && typeof parsed === 'object' && parsed.data && typeof parsed.data === 'object') {
|
||||
this.value = { ...clone(this.defaultValue), ...parsed.data };
|
||||
} else if (parsed && typeof parsed === 'object') {
|
||||
this.value = { ...clone(this.defaultValue), ...parsed };
|
||||
}
|
||||
this.loaded = true;
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') backupCorrupt(this.filePath);
|
||||
this.value = clone(this.defaultValue);
|
||||
this.loaded = false;
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
|
||||
save() {
|
||||
atomicWriteJson(this.filePath, {
|
||||
schemaVersion: SCHEMA_VERSION,
|
||||
updatedAt: nowIso(),
|
||||
data: this.value,
|
||||
});
|
||||
}
|
||||
|
||||
update(patch) {
|
||||
this.value = { ...this.value, ...patch };
|
||||
this.save();
|
||||
return this.value;
|
||||
}
|
||||
}
|
||||
|
||||
/** 通用 JSON 集合(数组) */
|
||||
class JsonCollection {
|
||||
/**
|
||||
* @param {string} filePath
|
||||
* @param {{ seed?: any[], normalize?: (item:any)=>any, idPrefix?: string }} options
|
||||
*/
|
||||
constructor(filePath, options = {}) {
|
||||
this.filePath = filePath;
|
||||
this.seed = clone(options.seed || []);
|
||||
this.normalize = options.normalize || ((item) => item);
|
||||
this.items = [];
|
||||
this.load();
|
||||
}
|
||||
|
||||
load() {
|
||||
try {
|
||||
const parsed = readJsonFile(this.filePath);
|
||||
const rawItems = Array.isArray(parsed) ? parsed : (Array.isArray(parsed.items) ? parsed.items : null);
|
||||
if (!rawItems) throw new Error('数据格式不是数组');
|
||||
this.items = rawItems.map((item) => this.safeNormalize(item)).filter(Boolean);
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') backupCorrupt(this.filePath);
|
||||
this.items = this.seed.map((item) => this.safeNormalize(item)).filter(Boolean);
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
|
||||
safeNormalize(item) {
|
||||
try {
|
||||
return this.normalize(item);
|
||||
} catch (err) {
|
||||
console.error(`[store] 忽略无效数据 (${path.basename(this.filePath)}): ${err.message}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
save() {
|
||||
atomicWriteJson(this.filePath, {
|
||||
schemaVersion: SCHEMA_VERSION,
|
||||
updatedAt: nowIso(),
|
||||
items: this.items,
|
||||
});
|
||||
}
|
||||
|
||||
list() {
|
||||
return this.items;
|
||||
}
|
||||
|
||||
find(id) {
|
||||
return this.items.find((item) => item.id === id) || null;
|
||||
}
|
||||
|
||||
insert(item) {
|
||||
const created = this.safeNormalize({ ...item, id: item.id || this.newId() });
|
||||
if (!created) throw new Error('数据校验失败');
|
||||
this.items.push(created);
|
||||
this.save();
|
||||
return created;
|
||||
}
|
||||
|
||||
update(id, patch) {
|
||||
const idx = this.items.findIndex((item) => item.id === id);
|
||||
if (idx === -1) return null;
|
||||
const merged = this.safeNormalize({ ...this.items[idx], ...patch, id });
|
||||
if (!merged) throw new Error('数据校验失败');
|
||||
this.items[idx] = merged;
|
||||
this.save();
|
||||
return merged;
|
||||
}
|
||||
|
||||
remove(id) {
|
||||
const before = this.items.length;
|
||||
this.items = this.items.filter((item) => item.id !== id);
|
||||
if (this.items.length === before) return false;
|
||||
this.save();
|
||||
return true;
|
||||
}
|
||||
|
||||
newId() {
|
||||
return `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化全部存储。
|
||||
* @param {string} dataDir
|
||||
* @param {{ appearancePresets: any[], contentPresets: any[], lrcPresets: any[], settings: any }} seed
|
||||
*/
|
||||
function createStores(dataDir, seed) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
return {
|
||||
dataDir,
|
||||
appearancePresets: new JsonCollection(path.join(dataDir, 'appearance-presets.json'), {
|
||||
seed: seed.appearancePresets,
|
||||
normalize: seed.normalizeAppearancePreset,
|
||||
}),
|
||||
contentPresets: new JsonCollection(path.join(dataDir, 'content-presets.json'), {
|
||||
seed: seed.contentPresets,
|
||||
normalize: seed.normalizeContentPreset,
|
||||
}),
|
||||
lrcPresets: new JsonCollection(path.join(dataDir, 'lrc-presets.json'), {
|
||||
seed: seed.lrcPresets,
|
||||
normalize: seed.normalizeLrcPreset,
|
||||
}),
|
||||
settings: new JsonDocument(path.join(dataDir, 'settings.json'), seed.settings),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SCHEMA_VERSION,
|
||||
JsonDocument,
|
||||
JsonCollection,
|
||||
createStores,
|
||||
atomicWriteJson,
|
||||
readJsonFile,
|
||||
};
|
||||
Reference in new issue
Block a user