Initial commit

This commit is contained in:
mxdyeah committed 2026-07-08 01:15:18 +08:00
commit acadc92e68
780 files changed
+468285

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
import { getScanStatus } from '../../utils/scanner';
export default defineEventHandler(() => {
return getScanStatus();
});
+9
View File
@@ -0,0 +1,9 @@
import { getQuery } from 'h3';
import { startScan } from '../../utils/scanner';
export default defineEventHandler((event) => {
const query = getQuery(event);
const force = query.force === 'true';
startScan(force);
return { ok: true, message: force ? 'Force scan started' : 'Scan started' };
});
+27
View File
@@ -0,0 +1,27 @@
import bcrypt from 'bcryptjs';
import { createError, readBody } from 'h3';
import db from '../../db';
import { cleanupExpiredSessions, createSession } from '../../utils/auth';
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const username = String(body?.username ?? '').trim();
const password = String(body?.password ?? '');
if (!username || !password) {
throw createError({ statusCode: 400, statusMessage: 'Username and password are required.' });
}
const user = db
.prepare('SELECT id, username, password_hash FROM users WHERE username = ?')
.get(username) as { id: number; username: string; password_hash: string } | undefined;
if (!user || !bcrypt.compareSync(password, user.password_hash)) {
throw createError({ statusCode: 401, statusMessage: 'Invalid credentials.' });
}
cleanupExpiredSessions();
createSession(event, user.id);
return { ok: true, username: user.username, display_name: user.username };
});
+6
View File
@@ -0,0 +1,6 @@
import { clearAuthSession } from '../../utils/auth';
export default defineEventHandler((event) => {
clearAuthSession(event);
return { ok: true };
});
+15
View File
@@ -0,0 +1,15 @@
import { getSessionUser } from '../../utils/auth';
export default defineEventHandler((event) => {
const user = getSessionUser(event);
if (!user) {
return { loggedIn: false };
}
return {
loggedIn: true,
username: user.username,
display_name: user.username,
musicList: user.musicList
};
});
+35
View File
@@ -0,0 +1,35 @@
import bcrypt from 'bcryptjs';
import { createError, readBody } from 'h3';
import db from '../../db';
import { cleanupExpiredSessions, createSession } from '../../utils/auth';
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const username = String(body?.username ?? '').trim();
const password = String(body?.password ?? '');
if (username.length < 3 || username.length > 32) {
throw createError({ statusCode: 400, statusMessage: 'Username must be 3-32 characters.' });
}
if (password.length < 6 || password.length > 72) {
throw createError({ statusCode: 400, statusMessage: 'Password must be 6-72 characters.' });
}
const existing = db
.prepare('SELECT id FROM users WHERE username = ?')
.get(username) as { id: number } | undefined;
if (existing) {
throw createError({ statusCode: 409, statusMessage: 'Username already exists.' });
}
const passwordHash = bcrypt.hashSync(password, 10);
const result = db
.prepare('INSERT INTO users (username, password_hash, created_at) VALUES (?, ?, ?)')
.run(username, passwordHash, Date.now());
cleanupExpiredSessions();
createSession(event, Number(result.lastInsertRowid));
return { ok: true, username, display_name: username };
});
+10
View File
@@ -0,0 +1,10 @@
import db from '../db';
import { requireUser } from '../utils/auth';
export default defineEventHandler(async (event) => {
const user = requireUser(event);
db.prepare('DELETE FROM play_history WHERE user_id = ?').run(user.id);
return { ok: true };
});
+58
View File
@@ -0,0 +1,58 @@
import { createError, readBody } from 'h3';
import db from '../db';
import { requireUser } from '../utils/auth';
export default defineEventHandler(async (event) => {
const user = requireUser(event);
const body = await readBody(event);
const filename = body?.filename;
const filenames = body?.filenames;
let fns: string[] = [];
if (Array.isArray(filenames)) {
fns = filenames.map(f => String(f).trim()).filter(Boolean);
} else if (filename) {
fns = [String(filename).trim()];
}
if (fns.length === 0) {
throw createError({ statusCode: 400, statusMessage: 'Filename or filenames are required.' });
}
// 准备插入 SQL 语句 (使用 ON CONFLICT 更新 played_at)
const insertStmt = db.prepare(`
INSERT INTO play_history (user_id, song_id, played_at)
SELECT ?, id, ? FROM songs WHERE filename = ?
ON CONFLICT(user_id, song_id) DO UPDATE SET played_at = excluded.played_at
`);
const now = Date.now();
// 运行事务批量插入
const runTransaction = db.transaction((filenamesList: string[]) => {
const len = filenamesList.length;
// 逆序处理以保持原有播放的时间先后顺序 (最旧的先插入,最新的最后插入)
for (let i = 0; i < len; i++) {
const fn = filenamesList[i];
// 稍微偏移几毫秒/秒以保持顺序
const playedAt = now - (len - 1 - i) * 1000;
insertStmt.run(user.id, playedAt, fn);
}
// 清理该用户超出 100 条的旧播放历史记录
db.prepare(`
DELETE FROM play_history
WHERE user_id = ? AND id NOT IN (
SELECT id FROM play_history
WHERE user_id = ?
ORDER BY played_at DESC
LIMIT 100
)
`).run(user.id, user.id);
});
runTransaction(fns);
return { ok: true };
});
+46
View File
@@ -0,0 +1,46 @@
import { createError, readBody } from 'h3';
import db from '../db';
import { requireUser } from '../utils/auth';
export default defineEventHandler(async (event) => {
const user = requireUser(event);
const body = await readBody(event);
const name = String(body?.name ?? '').trim();
if (!name) {
throw createError({ statusCode: 400, statusMessage: 'Track name is required.' });
}
// 检查歌曲是否存在于 songs 表中
const song = db.prepare('SELECT id FROM songs WHERE filename = ?').get(name) as { id: number } | undefined;
if (!song) {
throw createError({ statusCode: 404, statusMessage: 'Track not found in library.' });
}
// 检查是否已经收藏
const existing = db.prepare('SELECT id FROM favorites WHERE user_id = ? AND song_id = ?').get(user.id, song.id);
if (existing) {
// 取消收藏
db.prepare('DELETE FROM favorites WHERE user_id = ? AND song_id = ?').run(user.id, song.id);
} else {
// 添加收藏
db.prepare('INSERT INTO favorites (user_id, song_id, created_at) VALUES (?, ?, ?)').run(user.id, song.id, Date.now());
}
// 获取最新的收藏列表
const favRows = db.prepare(`
SELECT s.filename as fn
FROM favorites f
JOIN songs s ON f.song_id = s.id
WHERE f.user_id = ?
ORDER BY f.created_at DESC
`).all(user.id) as Array<{ fn: string }>;
const musicList = favRows.map((row, index) => ({
fn: row.fn,
id: index + 1
}));
return { ok: true, musicList };
});
+188
View File
@@ -0,0 +1,188 @@
import { readFileSync, statSync } from 'node:fs';
import { join, resolve, normalize } from 'node:path';
import { createError } from 'h3';
// 音乐文件的基础路径
const MUSIC_BASE_PATH = '/nvme1/collectedmod';
export default defineEventHandler(async (event) => {
try {
// 获取请求的文件路径
const params = getRouterParams(event);
const pathParam = params.path;
if (!pathParam) {
throw createError({
statusCode: 400,
statusMessage: 'Missing file path parameter'
});
}
// 构建完整的文件路径
// 规范化路径以防止路径遍历攻击
const decodedPath = decodeURIComponent(pathParam);
const requestedPath = normalize(decodedPath);
const fullPath = resolve(join(MUSIC_BASE_PATH, requestedPath));
// 安全检查:确保请求的路径在基础路径内
const basePathResolved = resolve(MUSIC_BASE_PATH);
if (!fullPath.startsWith(basePathResolved)) {
throw createError({
statusCode: 403,
statusMessage: 'Access denied: Path traversal detected'
});
}
// 检查文件是否存在
let stats;
try {
stats = statSync(fullPath);
} catch (err: any) {
if (err.code === 'ENOENT') {
throw createError({
statusCode: 404,
statusMessage: 'File not found'
});
}
throw err;
}
// 检查是否是文件(不是目录)
if (!stats.isFile()) {
throw createError({
statusCode: 400,
statusMessage: 'Path is not a file'
});
}
// 读取文件内容
const fileBuffer = readFileSync(fullPath);
// 根据文件扩展名设置正确的 Content-Type
const ext = fullPath.split('.').pop()?.toLowerCase();
const contentTypeMap: Record<string, string> = {
'mod': 'audio/mod',
'xm': 'audio/xm',
'it': 'audio/it',
's3m': 'audio/s3m',
'umx': 'audio/umx',
'mptm': 'audio/x-mod',
'stm': 'audio/x-mod',
'mtm': 'audio/x-mod',
'ptm': 'audio/x-mod',
'far': 'audio/x-mod',
'ult': 'audio/x-mod',
'669': 'audio/x-mod',
'amf': 'audio/x-mod',
'dsm': 'audio/x-mod',
'mdl': 'audio/x-mod',
'med': 'audio/x-mod',
'okt': 'audio/x-mod',
'psm': 'audio/x-mod',
'dbm': 'audio/x-mod',
'imf': 'audio/x-mod',
'j2b': 'audio/x-mod',
'mo3': 'audio/x-mod',
'gdm': 'audio/x-mod',
'stp': 'audio/x-mod',
'sfx': 'audio/x-mod',
'sfx2': 'audio/x-mod',
'itp': 'audio/x-mod',
'dtm': 'audio/x-mod',
'mt2': 'audio/x-mod',
'symmod': 'audio/x-mod',
'c67': 'audio/x-mod',
'ams': 'audio/x-mod',
'stx': 'audio/x-mod',
'667': 'audio/x-mod',
'cba': 'audio/x-mod',
'digi': 'audio/x-mod',
'dmf': 'audio/x-mod',
'dsym': 'audio/x-mod',
'etx': 'audio/x-mod',
'fc': 'audio/x-mod',
'fc13': 'audio/x-mod',
'fc14': 'audio/x-mod',
'fmt': 'audio/x-mod',
'ftm': 'audio/x-mod',
'gmc': 'audio/x-mod',
'gt2': 'audio/x-mod',
'gtk': 'audio/x-mod',
'ice': 'audio/x-mod',
'ims': 'audio/x-mod',
'm15': 'audio/x-mod',
'mms': 'audio/x-mod',
'mus': 'audio/x-mod',
'oxm': 'audio/x-mod',
'plm': 'audio/x-mod',
'pt36': 'audio/x-mod',
'puma': 'audio/x-mod',
'rtm': 'audio/x-mod',
'smod': 'audio/x-mod',
'st26': 'audio/x-mod',
'stk': 'audio/x-mod',
'wow': 'audio/x-mod',
'xmf': 'audio/x-mod',
'mdz': 'audio/x-mod',
's3z': 'audio/x-mod',
'xmz': 'audio/x-mod',
'itz': 'audio/x-mod',
'mptmz': 'audio/x-mod',
'mdr': 'audio/x-mod',
'ogg': 'audio/ogg',
'mp3': 'audio/mpeg',
'wav': 'audio/wav',
'flac': 'audio/flac'
};
const contentType = contentTypeMap[ext || ''] || 'application/octet-stream';
// 设置响应头
setHeader(event, 'Content-Type', contentType);
setHeader(event, 'Content-Length', stats.size);
setHeader(event, 'Cache-Control', 'public, max-age=3600');
setHeader(event, 'Accept-Ranges', 'bytes');
// 支持 Range 请求(用于音频流式播放)
const rangeHeader = getHeader(event, 'range');
const rangeValue = Array.isArray(rangeHeader) ? rangeHeader[0] : rangeHeader;
if (typeof rangeValue === 'string' && rangeValue.startsWith('bytes=')) {
const parts = rangeValue.replace(/bytes=/, '').split('-');
const startText = parts[0] ?? '';
const endText = parts[1] ?? '';
let start: number;
let end: number;
if (startText === '' && endText !== '') {
const suffixLength = Math.max(0, parseInt(endText, 10) || 0);
start = Math.max(0, stats.size - suffixLength);
end = stats.size - 1;
} else {
start = Math.max(0, parseInt(startText, 10) || 0);
end = endText ? parseInt(endText, 10) || stats.size - 1 : stats.size - 1;
}
if (start <= end && start < stats.size) {
end = Math.min(end, stats.size - 1);
const chunkSize = end - start + 1;
const chunk = fileBuffer.slice(start, end + 1);
setHeader(event, 'Content-Range', `bytes ${start}-${end}/${stats.size}`);
setHeader(event, 'Content-Length', chunkSize);
setResponseStatus(event, 206); // Partial Content
return chunk;
}
}
return fileBuffer;
} catch (error: any) {
if (error.statusCode) {
throw error;
}
throw createError({
statusCode: 500,
statusMessage: error.message || 'Internal server error'
});
}
});
+74
View File
@@ -0,0 +1,74 @@
import { statSync } from 'node:fs';
import { join, resolve, normalize, basename, extname } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { tmpdir } from 'node:os';
import { readFileSync, unlinkSync } from 'node:fs';
import { createError } from 'h3';
const execFileAsync = promisify(execFile);
const MUSIC_BASE_PATH = '/nvme1/collectedmod';
const CONVERTIBLE_EXTS = new Set(['xm', 'mod', 'it', 's3m', 'umx', 'mptm', 'stm', 'mtm', 'ptm', 'far', 'ult', '669', 'amf', 'dsm', 'mdl', 'med', 'okt', 'psm', 'dbm', 'imf', 'j2b', 'mo3', 'gdm', 'stp', 'sfx', 'sfx2', 'itp', 'dtm', 'mt2', 'symmod', 'c67', 'ams', 'stx', '667', 'cba', 'digi', 'dmf', 'dsym', 'etx', 'fc', 'fc13', 'fc14', 'fmt', 'ftm', 'gmc', 'gt2', 'gtk', 'ice', 'ims', 'm15', 'mms', 'mus', 'oxm', 'plm', 'pt36', 'puma', 'rtm', 'smod', 'st26', 'stk', 'wow', 'xmf', 'mdz', 's3z', 'xmz', 'itz', 'mptmz', 'mdr']);
export default defineEventHandler(async (event) => {
const query = getQuery(event);
const pathParam = query.path as string;
if (!pathParam) {
throw createError({ statusCode: 400, statusMessage: 'Missing path parameter' });
}
const decodedPath = decodeURIComponent(pathParam);
const requestedPath = normalize(decodedPath);
const fullPath = resolve(join(MUSIC_BASE_PATH, requestedPath));
if (!fullPath.startsWith(resolve(MUSIC_BASE_PATH))) {
throw createError({ statusCode: 403, statusMessage: 'Access denied' });
}
let stats;
try {
stats = statSync(fullPath);
} catch (err: any) {
if (err.code === 'ENOENT') {
throw createError({ statusCode: 404, statusMessage: 'File not found' });
}
throw err;
}
if (!stats.isFile()) {
throw createError({ statusCode: 400, statusMessage: 'Path is not a file' });
}
const ext = extname(fullPath).slice(1).toLowerCase();
// 支持所有 ffmpeg 可处理的音频格式(引擎3:全部转为MP3播放)
const SUPPORTED_EXTS = new Set([...CONVERTIBLE_EXTS, 'mp3', 'ogg', 'wav', 'flac', 'aac', 'wma', 'm4a', 'opus', 'aiff', 'au', 'ra', 'amr', 'ac3', 'dts', 'tta', 'wv', 'ape', 'mp2', 'mp1', 'voc', 'pcm', 'adpcm', 'gsm', 'vqf', 'tak', 'ofr', 'spx', 'cda']);
if (!SUPPORTED_EXTS.has(ext)) {
throw createError({ statusCode: 400, statusMessage: `Cannot convert .${ext} to MP3` });
}
const baseName = basename(fullPath, extname(fullPath));
const tmpOut = join(tmpdir(), `tp_${Date.now()}_${Math.random().toString(36).slice(2)}.mp3`);
try {
await execFileAsync('ffmpeg', [
'-y',
'-i', fullPath,
'-q:a', '2',
'-map', 'a',
tmpOut,
], { timeout: 120000 });
const mp3Buffer = readFileSync(tmpOut);
setHeader(event, 'Content-Type', 'audio/mpeg');
setHeader(event, 'Content-Disposition', `attachment; filename="${encodeURIComponent(baseName)}.mp3"`);
setHeader(event, 'Cache-Control', 'no-store');
return mp3Buffer;
} catch (err: any) {
throw createError({ statusCode: 500, statusMessage: `Conversion failed: ${err.message}` });
} finally {
try { unlinkSync(tmpOut); } catch {}
}
});
+26
View File
@@ -0,0 +1,26 @@
import { createError } from "h3";
import db from "../../db";
export default defineEventHandler(async (event) => {
const params = getRouterParams(event);
const idParam = params.id;
const parsedId = idParam ? Number.parseInt(String(idParam), 10) : NaN;
if (!Number.isFinite(parsedId) || parsedId < 1) {
throw createError({
statusCode: 400,
statusMessage: "Invalid song id",
});
}
const song = db.prepare('SELECT id, filename as fileName FROM songs WHERE id = ?').get(parsedId) as { id: number, fileName: string } | undefined;
if (!song) {
throw createError({
statusCode: 404,
statusMessage: "Song not found",
});
}
return song;
});
+193
View File
@@ -0,0 +1,193 @@
import { getQuery } from 'h3';
import db from '../db';
import { getSessionUser } from '../utils/auth';
export default defineEventHandler(async (event) => {
const query = getQuery(event);
const page = Math.max(1, parseInt(String(query.page || '1'), 10));
const limit = Math.max(1, parseInt(String(query.limit || '100'), 10));
const search = String(query.search || '').trim();
const extensionsRaw = String(query.extensions || '').trim();
const sort = parseInt(String(query.sort || '0'), 10);
const mode = parseInt(String(query.mode || '0'), 10);
const filenamesStr = String(query.filenames || '').trim();
const channels = String(query.channels || 'all').trim().toLowerCase();
const size = String(query.size || 'all').trim().toLowerCase();
const trackerName = String(query.tracker_name || '').trim();
// 构建 SQL 查询条件和绑定参数
let joinClause = '';
const conditions: string[] = [];
const params: any[] = [];
const user = getSessionUser(event);
// 1. 根据模式筛选 (全部 / 收藏 / 历史)
if (mode === 1) {
// 收藏模式
if (!user) {
return { songs: [], total: 0, page, limit, totalPages: 0 };
}
joinClause = 'INNER JOIN favorites f ON songs.id = f.song_id';
conditions.push('f.user_id = ?');
params.push(user.id);
} else if (mode === 2) {
// 历史模式
if (user) {
// 已登录用户,拉取云端历史
joinClause = 'INNER JOIN play_history h ON songs.id = h.song_id';
conditions.push('h.user_id = ?');
params.push(user.id);
} else {
// 未登录用户,通过传入的文件名列表拉取
if (!filenamesStr) {
return { songs: [], total: 0, page, limit, totalPages: 0 };
}
const historyFilenames = filenamesStr.split(',').map(f => f.trim()).filter(Boolean);
if (historyFilenames.length === 0) {
return { songs: [], total: 0, page, limit, totalPages: 0 };
}
const placeholders = historyFilenames.map(() => '?').join(',');
conditions.push(`songs.filename IN (${placeholders})`);
params.push(...historyFilenames);
}
}
// 2. 搜索条件(支持文件名、歌曲标题和元数据乐器模糊匹配)
if (search) {
conditions.push('(songs.filename LIKE ? OR songs.title LIKE ? OR songs.message LIKE ? OR songs.instruments LIKE ?)');
params.push(`%${search}%`, `%${search}%`, `%${search}%`, `%${search}%`);
}
// 3. 多选格式筛选(逗号分隔扩展名列表,空字符串表示不限制)
if (extensionsRaw) {
const extList = extensionsRaw.split(',').map(e => e.trim().toLowerCase()).filter(Boolean);
if (extList.length > 0) {
const placeholders = extList.map(() => '?').join(',');
conditions.push(`songs.extension IN (${placeholders})`);
params.push(...extList);
}
}
// 4.1. 通道数筛选
if (channels !== 'all') {
if (channels === '4') {
conditions.push('songs.channels = 4');
} else if (channels === '8') {
conditions.push('songs.channels = 8');
} else if (channels === 'multi') {
conditions.push('songs.channels > 8');
}
}
// 4.2. 文件大小筛选
if (size !== 'all') {
if (size === 'small') {
conditions.push('songs.file_size < 102400'); // < 100KB
} else if (size === 'medium') {
conditions.push('songs.file_size >= 102400 AND songs.file_size <= 1048576'); // 100KB - 1MB
} else if (size === 'large') {
conditions.push('songs.file_size > 1048576'); // > 1MB
}
}
// 4.3. Tracker Name 筛选
if (trackerName && trackerName !== 'all') {
conditions.push('songs.tracker_name LIKE ?');
params.push(`%${trackerName}%`);
}
// 组装 WHERE 语句
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
// 5. 排序方式
let orderBy = 'ORDER BY songs.id ASC';
if (sort === 0) {
if (mode === 1) {
orderBy = 'ORDER BY f.created_at DESC';
} else if (mode === 2 && user) {
orderBy = 'ORDER BY h.played_at DESC';
} else {
orderBy = 'ORDER BY songs.id ASC';
}
} else {
switch (sort) {
case 1:
orderBy = 'ORDER BY songs.id DESC';
break;
case 2:
orderBy = 'ORDER BY songs.title COLLATE NOCASE ASC';
break;
case 3:
orderBy = 'ORDER BY songs.title COLLATE NOCASE DESC';
break;
case 4:
orderBy = 'ORDER BY songs.filename COLLATE NOCASE ASC';
break;
case 5:
orderBy = 'ORDER BY songs.filename COLLATE NOCASE DESC';
break;
case 6:
orderBy = 'ORDER BY songs.file_size ASC';
break;
case 7:
orderBy = 'ORDER BY songs.file_size DESC';
break;
case 8:
orderBy = 'ORDER BY songs.file_mtime ASC';
break;
case 9:
orderBy = 'ORDER BY songs.file_mtime DESC';
break;
default:
orderBy = 'ORDER BY songs.id ASC';
break;
}
}
// 执行 COUNT 获取总条数
const countSql = `SELECT COUNT(*) as count FROM songs ${joinClause} ${whereClause}`;
const countResult = db.prepare(countSql).get(...params) as { count: number };
const total = countResult.count;
const totalPages = Math.ceil(total / limit);
// 执行分页数据查询
const offset = (page - 1) * limit;
const dataSql = `SELECT songs.id, songs.filename as fn, songs.title, songs.artist, songs.extension, songs.file_size, songs.file_mtime, songs.playable, songs.tracker_format, songs.channels, songs.tracker_name, songs.message, songs.instruments, songs.metadata
FROM songs ${joinClause} ${whereClause} ${orderBy} LIMIT ? OFFSET ?`;
const songs = db.prepare(dataSql).all(...params, limit, offset) as any[];
// 如果是历史模式且未登录,根据前端传入的文件名顺序重新对结果进行排序,以便保持历史播放的时间先后顺序
if (mode === 2 && !user && filenamesStr) {
const historyFilenames = filenamesStr.split(',').map(f => f.trim()).filter(Boolean);
const songMap = new Map<string, any>();
for (const song of songs) {
songMap.set(song.fn, song);
}
const sortedSongs: any[] = [];
for (const fn of historyFilenames) {
const song = songMap.get(fn);
if (song) {
sortedSongs.push(song);
}
}
return {
songs: sortedSongs,
total,
page,
limit,
totalPages
};
}
return {
songs,
total,
page,
limit,
totalPages
};
});
+169
View File
@@ -0,0 +1,169 @@
import { getQuery, createError } from 'h3';
import db from '../../db';
import { getSessionUser } from '../../utils/auth';
export default defineEventHandler(async (event) => {
const query = getQuery(event);
const currentFilename = String(query.currentFilename || '').trim();
const direction = String(query.direction || 'next').trim().toLowerCase();
const search = String(query.search || '').trim();
const extensionsRaw = String(query.extensions || '').trim();
const sort = parseInt(String(query.sort || '0'), 10);
const mode = parseInt(String(query.mode || '0'), 10);
const filenamesStr = String(query.filenames || '').trim();
const channels = String(query.channels || 'all').trim().toLowerCase();
const size = String(query.size || 'all').trim().toLowerCase();
if (!currentFilename) {
throw createError({ statusCode: 400, statusMessage: 'currentFilename is required' });
}
let filenames: string[] = [];
const user = getSessionUser(event);
if (mode === 2 && (!user || filenamesStr)) {
// 历史记录模式,直接使用前端传入的有序文件名列表(以保持准确的历史顺序)
filenames = filenamesStr.split(',').map(f => f.trim()).filter(Boolean);
} else {
// 构建 SQL
let joinClause = '';
const conditions: string[] = [];
const params: any[] = [];
if (mode === 1) {
// 收藏模式
if (!user) {
return { song: null };
}
joinClause = 'INNER JOIN favorites f ON songs.id = f.song_id';
conditions.push('f.user_id = ?');
params.push(user.id);
} else if (mode === 2 && user) {
// 历史模式(已登录)
joinClause = 'INNER JOIN play_history h ON songs.id = h.song_id';
conditions.push('h.user_id = ?');
params.push(user.id);
}
if (search) {
conditions.push('(songs.filename LIKE ? OR songs.title LIKE ? OR songs.message LIKE ? OR songs.instruments LIKE ?)');
params.push(`%${search}%`, `%${search}%`, `%${search}%`, `%${search}%`);
}
if (extensionsRaw) {
const extList = extensionsRaw.split(',').map(e => e.trim().toLowerCase()).filter(Boolean);
if (extList.length > 0) {
const placeholders = extList.map(() => '?').join(',');
conditions.push(`songs.extension IN (${placeholders})`);
params.push(...extList);
}
}
if (channels !== 'all') {
if (channels === '4') {
conditions.push('songs.channels = 4');
} else if (channels === '8') {
conditions.push('songs.channels = 8');
} else if (channels === 'multi') {
conditions.push('songs.channels > 8');
}
}
if (size !== 'all') {
if (size === 'small') {
conditions.push('songs.file_size < 102400');
} else if (size === 'medium') {
conditions.push('songs.file_size >= 102400 AND songs.file_size <= 1048576');
} else if (size === 'large') {
conditions.push('songs.file_size > 1048576');
}
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
// 同步 songs.get.ts 的排序逻辑
let orderBy = 'ORDER BY songs.id ASC';
if (sort === 0) {
if (mode === 1) {
orderBy = 'ORDER BY f.created_at DESC';
} else if (mode === 2 && user) {
orderBy = 'ORDER BY h.played_at DESC';
} else {
orderBy = 'ORDER BY songs.id ASC';
}
} else {
switch (sort) {
case 1:
orderBy = 'ORDER BY songs.id DESC';
break;
case 2:
orderBy = 'ORDER BY songs.title COLLATE NOCASE ASC';
break;
case 3:
orderBy = 'ORDER BY songs.title COLLATE NOCASE DESC';
break;
case 4:
orderBy = 'ORDER BY songs.filename COLLATE NOCASE ASC';
break;
case 5:
orderBy = 'ORDER BY songs.filename COLLATE NOCASE DESC';
break;
case 6:
orderBy = 'ORDER BY songs.file_size ASC';
break;
case 7:
orderBy = 'ORDER BY songs.file_size DESC';
break;
case 8:
orderBy = 'ORDER BY songs.file_mtime ASC';
break;
case 9:
orderBy = 'ORDER BY songs.file_mtime DESC';
break;
default:
orderBy = 'ORDER BY songs.id ASC';
break;
}
}
const sql = `SELECT songs.filename FROM songs ${joinClause} ${whereClause} ${orderBy}`;
const result = db.prepare(sql).all(...params) as Array<{ filename: string }>;
filenames = result.map(r => r.filename);
}
if (filenames.length === 0) {
return { song: null };
}
// 2. 在有序数组中寻找当前歌曲的位置
const currentIndex = filenames.indexOf(currentFilename);
if (currentIndex === -1) {
// 如果当前播放的歌曲不在列表中(可能是因为刚刚切换了搜索/过滤条件)
// 那我们默认返回列表中的第一首
const targetFilename = filenames[0]!;
const song = db.prepare('SELECT id, filename as fn, title, artist, extension, playable, tracker_format, channels, tracker_name, message, instruments, metadata FROM songs WHERE filename = ?').get(targetFilename);
return { song };
}
// 3. 计算相邻歌曲索引
let targetIndex = -1;
if (direction === 'next') {
targetIndex = currentIndex + 1;
// 如果是最后一首,可以循环播放到第一首,或者根据需要返回 null 停止
if (targetIndex >= filenames.length) {
targetIndex = 0; // 循环
}
} else {
targetIndex = currentIndex - 1;
if (targetIndex < 0) {
targetIndex = filenames.length - 1; // 循环到最后一首
}
}
const targetFilename = filenames[targetIndex]!;
const song = db.prepare('SELECT id, filename as fn, title, artist, extension, playable, tracker_format, channels, tracker_name, message, instruments, metadata FROM songs WHERE filename = ?').get(targetFilename);
return { song };
});
+44
View File
@@ -0,0 +1,44 @@
import db from '../../db';
// 引擎标签映射
const ENGINE_TAGS: Record<string, string> = {
// Bassoon + Chiptune3
xm: 'bc', mod: 'bc',
// Chiptune3 (libopenmpt) — 68 种 tracker 格式
it: 'c', s3m: 'c', umx: 'c', mptm: 'c', stm: 'c', mtm: 'c', ptm: 'c',
far: 'c', ult: 'c', '669': 'c', amf: 'c', dsm: 'c', mdl: 'c', med: 'c',
okt: 'c', psm: 'c', dbm: 'c', imf: 'c', j2b: 'c', mo3: 'c', gdm: 'c',
stp: 'c', sfx: 'c', sfx2: 'c', itp: 'c', dtm: 'c', mt2: 'c', symmod: 'c',
c67: 'c', ams: 'c', stx: 'c', '667': 'c', cba: 'c', digi: 'c', dmf: 'c',
dsym: 'c', etx: 'c', fc: 'c', fc13: 'c', fc14: 'c', fmt: 'c', ftm: 'c',
gmc: 'c', gt2: 'c', gtk: 'c', ice: 'c', ims: 'c', m15: 'c', mms: 'c',
mus: 'c', oxm: 'c', plm: 'c', pt36: 'c', puma: 'c', rtm: 'c', smod: 'c',
st26: 'c', stk: 'c', wow: 'c', xmf: 'c', mdz: 'c', s3z: 'c', xmz: 'c',
itz: 'c', mptmz: 'c', mdr: 'c',
// Native HTML5 Audio
mp3: 'n', ogg: 'n', wav: 'n', flac: 'n',
// FFmpeg convertible
aac: 'f', opus: 'f', aiff: 'f', m4a: 'f', wma: 'f',
ac3: 'f', dts: 'f', ape: 'f', wv: 'f', tta: 'f', mp2: 'f', amr: 'f',
ra: 'f', au: 'f', voc: 'f', pcm: 'f', spx: 'f', tak: 'f', cda: 'f',
adpcm: 'f', gsm: 'f', vqf: 'f', ofr: 'f', mp1: 'f',
};
export default defineEventHandler(async () => {
const rows = db.prepare(`
SELECT extension, COUNT(*) as count
FROM songs
WHERE extension IS NOT NULL AND extension != ''
AND playable = 1
GROUP BY extension
ORDER BY count DESC
`).all() as Array<{ extension: string; count: number }>;
const formats = rows.map(row => ({
extension: row.extension.toLowerCase(),
count: row.count,
engine: ENGINE_TAGS[row.extension.toLowerCase()] || 'f',
}));
return formats;
});
+97
View File
@@ -0,0 +1,97 @@
import { getQuery } from 'h3';
import db from '../../db';
import { getSessionUser } from '../../utils/auth';
export default defineEventHandler(async (event) => {
const query = getQuery(event);
const search = String(query.search || '').trim();
const extensionsRaw = String(query.extensions || '').trim();
const mode = parseInt(String(query.mode || '0'), 10);
const filenamesStr = String(query.filenames || '').trim();
const channels = String(query.channels || 'all').trim().toLowerCase();
const size = String(query.size || 'all').trim().toLowerCase();
const trackerName = String(query.tracker_name || '').trim();
const user = getSessionUser(event);
let joinClause = '';
const conditions: string[] = [];
const params: any[] = [];
// 1. 根据模式筛选
if (mode === 1) {
if (!user) {
return { song: null };
}
joinClause = 'INNER JOIN favorites f ON songs.id = f.song_id';
conditions.push('f.user_id = ?');
params.push(user.id);
} else if (mode === 2) {
if (user) {
joinClause = 'INNER JOIN play_history h ON songs.id = h.song_id';
conditions.push('h.user_id = ?');
params.push(user.id);
} else {
if (!filenamesStr) {
return { song: null };
}
const historyFilenames = filenamesStr.split(',').map(f => f.trim()).filter(Boolean);
if (historyFilenames.length === 0) {
return { song: null };
}
const placeholders = historyFilenames.map(() => '?').join(',');
conditions.push(`songs.filename IN (${placeholders})`);
params.push(...historyFilenames);
}
}
// 2. 搜索条件
if (search) {
conditions.push('(songs.filename LIKE ? OR songs.title LIKE ? OR songs.message LIKE ? OR songs.instruments LIKE ?)');
params.push(`%${search}%`, `%${search}%`, `%${search}%`, `%${search}%`);
}
// 3. 多选格式筛选
if (extensionsRaw) {
const extList = extensionsRaw.split(',').map(e => e.trim().toLowerCase()).filter(Boolean);
if (extList.length > 0) {
const placeholders = extList.map(() => '?').join(',');
conditions.push(`songs.extension IN (${placeholders})`);
params.push(...extList);
}
}
if (channels !== 'all') {
if (channels === '4') {
conditions.push('songs.channels = 4');
} else if (channels === '8') {
conditions.push('songs.channels = 8');
} else if (channels === 'multi') {
conditions.push('songs.channels > 8');
}
}
if (size !== 'all') {
if (size === 'small') {
conditions.push('songs.file_size < 102400');
} else if (size === 'medium') {
conditions.push('songs.file_size >= 102400 AND songs.file_size <= 1048576');
} else if (size === 'large') {
conditions.push('songs.file_size > 1048576');
}
}
if (trackerName && trackerName !== 'all') {
conditions.push('songs.tracker_name LIKE ?');
params.push(`%${trackerName}%`);
}
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
const sql = `SELECT songs.id, songs.filename as fn, songs.title, songs.artist, songs.extension, songs.file_size, songs.file_mtime, songs.playable, songs.tracker_format, songs.channels, songs.tracker_name, songs.message, songs.instruments, songs.metadata
FROM songs ${joinClause} ${whereClause} ORDER BY RANDOM() LIMIT 1`;
const song = db.prepare(sql).get(...params);
return { song: song || null };
});
+9
View File
@@ -0,0 +1,9 @@
import { requireUser } from '../utils/auth';
export default defineEventHandler((event) => {
const user = requireUser(event);
return {
display_name: user.username,
musicList: user.musicList
};
});
+172
View File
@@ -0,0 +1,172 @@
// @ts-expect-error better-sqlite3 does not have builtin types
import Database from 'better-sqlite3';
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
const dataDir = join(process.cwd(), 'data');
mkdirSync(dataDir, { recursive: true });
const db = new Database(join(dataDir, 'app.sqlite'));
try {
db.exec('ALTER TABLE songs ADD COLUMN artist TEXT');
} catch (e) {
// Ignore error if column already exists
}
try {
db.exec('ALTER TABLE songs ADD COLUMN tracker_name TEXT');
} catch (e) {}
try {
db.exec('ALTER TABLE songs ADD COLUMN message TEXT');
} catch (e) {}
try {
db.exec('ALTER TABLE songs ADD COLUMN instruments TEXT');
} catch (e) {}
db.pragma('journal_mode = WAL');
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at INTEGER NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_sessions_token_hash ON sessions(token_hash);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE TABLE IF NOT EXISTS songs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL UNIQUE,
title TEXT,
artist TEXT,
extension TEXT,
file_size INTEGER,
file_mtime INTEGER,
playable INTEGER NOT NULL DEFAULT 1,
tracker_format TEXT,
channels INTEGER,
tracker_name TEXT,
message TEXT,
instruments TEXT,
metadata TEXT
);
CREATE INDEX IF NOT EXISTS idx_songs_filename ON songs(filename);
CREATE INDEX IF NOT EXISTS idx_songs_extension ON songs(extension);
CREATE INDEX IF NOT EXISTS idx_songs_playable ON songs(playable);
CREATE INDEX IF NOT EXISTS idx_songs_tracker_name ON songs(tracker_name);
CREATE TABLE IF NOT EXISTS favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
song_id INTEGER NOT NULL,
created_at INTEGER NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY(song_id) REFERENCES songs(id) ON DELETE CASCADE,
UNIQUE(user_id, song_id)
);
CREATE INDEX IF NOT EXISTS idx_favorites_user_id ON favorites(user_id);
CREATE INDEX IF NOT EXISTS idx_favorites_song_id ON favorites(song_id);
CREATE TABLE IF NOT EXISTS play_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
song_id INTEGER NOT NULL,
played_at INTEGER NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY(song_id) REFERENCES songs(id) ON DELETE CASCADE,
UNIQUE(user_id, song_id)
);
CREATE INDEX IF NOT EXISTS idx_play_history_user_id ON play_history(user_id);
CREATE INDEX IF NOT EXISTS idx_play_history_played_at ON play_history(played_at);
`);
// 迁移旧的 music_list JSON 字段到 favorites 表,并删除废弃的 music_list 字段
try {
// 检查 users 表中是否存在 music_list 列
const info = db.pragma("table_info(users)") as Array<{ name: string }>;
const hasMusicListColumn = info.some(col => col.name === 'music_list');
if (hasMusicListColumn) {
const usersWithOldFavorites = db.prepare(`
SELECT id, music_list FROM users
WHERE music_list IS NOT NULL AND music_list != '[]'
`).all() as Array<{ id: number; music_list: string }>;
if (usersWithOldFavorites.length > 0) {
console.log(`Found ${usersWithOldFavorites.length} users with old favorites. Migrating to favorites table...`);
const insertFavorite = db.prepare(`
INSERT OR IGNORE INTO favorites (user_id, song_id, created_at)
VALUES (?, ?, ?)
`);
const getSongId = db.prepare(`SELECT id FROM songs WHERE filename = ?`);
// 启动事务
const migrateTx = db.transaction(() => {
const now = Date.now();
for (const userRow of usersWithOldFavorites) {
try {
const list = JSON.parse(userRow.music_list);
if (Array.isArray(list)) {
for (const item of list) {
const fn = typeof item === 'object' && item !== null ? item.fn : (typeof item === 'string' ? item : null);
if (fn && typeof fn === 'string') {
const song = getSongId.get(fn.trim()) as { id: number } | undefined;
if (song) {
insertFavorite.run(userRow.id, song.id, now);
}
}
}
}
} catch (err) {
console.error(`Failed to migrate favorites for user ID ${userRow.id}:`, err);
}
}
});
migrateTx();
console.log('Favorites migration completed successfully.');
}
// 物理删除已经废弃的 music_list 字段
try {
db.exec('ALTER TABLE users DROP COLUMN music_list');
console.log('Successfully dropped obsolete column users.music_list');
} catch (dropErr) {
console.error('Failed to drop column users.music_list:', dropErr);
}
}
} catch (e) {
console.error('Error during favorites migration and column cleanup:', e);
}
const count = db.prepare('SELECT COUNT(*) as count FROM songs').get() as { count: number };
if (count.count === 0) {
import('./utils/scanner').then(({ startScan }) => {
console.log('Songs table is empty. Starting background music scan...');
startScan();
}).catch(err => {
console.error('Failed to start automatic songs scan:', err);
});
}
export default db;
+17
View File
@@ -0,0 +1,17 @@
import { getRequestURL } from "h3";
export default defineEventHandler((event) => {
const requestUrl = getRequestURL(event);
const siteUrl = requestUrl.origin;
const robots = [
"User-agent: *",
"Allow: /",
"Disallow: /api/admin/",
"Disallow: /api/auth/",
`Sitemap: ${siteUrl}/sitemap.xml`,
].join("\n");
setHeader(event, "Content-Type", "text/plain; charset=utf-8");
return robots;
});
+43
View File
@@ -0,0 +1,43 @@
import { getRequestURL } from "h3";
import db from "../db";
export default defineEventHandler((event) => {
const requestUrl = getRequestURL(event);
const siteUrl = requestUrl.origin;
// 查询所有 playable = 1 的歌曲
const songs = db.prepare(
"SELECT id, filename FROM songs WHERE playable = 1"
).all() as Array<{ id: number; filename: string }>;
// 生成 XML 内容
const urls: string[] = [];
// 添加首页
urls.push(`
<url>
<loc>${siteUrl}/</loc>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>`);
// 循环添加歌曲页面
for (const song of songs) {
const encodedName = encodeURIComponent(song.filename);
const loc = `${siteUrl}/song/${song.id}/${encodedName}`;
urls.push(`
<url>
<loc>${loc}</loc>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>`);
}
const sitemapXml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls.join("")}
</urlset>`;
setHeader(event, "Content-Type", "application/xml; charset=utf-8");
return sitemapXml;
});
+95
View File
@@ -0,0 +1,95 @@
import { createHash, randomBytes } from 'node:crypto';
import { createError, deleteCookie, getCookie, setCookie } from 'h3';
import db from '../db';
const SESSION_TTL_MS = 1000 * 60 * 60 * 24 * 7;
function hashToken(token: string) {
return createHash('sha256').update(token).digest('hex');
}
export function cleanupExpiredSessions() {
db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(Date.now());
}
export function createSession(event: any, userId: number) {
const token = randomBytes(32).toString('hex');
const tokenHash = hashToken(token);
const expiresAt = Date.now() + SESSION_TTL_MS;
db.prepare(
'INSERT INTO sessions (user_id, token_hash, expires_at) VALUES (?, ?, ?)'
).run(userId, tokenHash, expiresAt);
setCookie(event, 'session', token, {
httpOnly: true,
sameSite: 'lax',
path: '/',
maxAge: Math.floor(SESSION_TTL_MS / 1000)
});
}
export function clearAuthSession(event: any) {
const token = getCookie(event, 'session');
if (token) {
const tokenHash = hashToken(token);
db.prepare('DELETE FROM sessions WHERE token_hash = ?').run(tokenHash);
}
deleteCookie(event, 'session', { path: '/' });
}
export type SessionUser = {
id: number;
username: string;
musicList: Array<{ fn: string; id: number }>;
};
export function getSessionUser(event: any): SessionUser | null {
const token = getCookie(event, 'session');
if (!token) return null;
const tokenHash = hashToken(token);
const now = Date.now();
const session = db
.prepare('SELECT user_id FROM sessions WHERE token_hash = ? AND expires_at > ?')
.get(tokenHash, now) as { user_id: number } | undefined;
if (!session) return null;
const user = db
.prepare('SELECT id, username FROM users WHERE id = ?')
.get(session.user_id) as
| { id: number; username: string }
| undefined;
if (!user) {
return null;
}
const favRows = db.prepare(`
SELECT s.id, s.filename as fn
FROM favorites f
JOIN songs s ON f.song_id = s.id
WHERE f.user_id = ?
ORDER BY f.created_at DESC
`).all(user.id) as Array<{ id: number; fn: string }>;
const musicList = favRows.map((row) => ({
fn: row.fn,
id: row.id
}));
return {
id: user.id,
username: user.username,
musicList
};
}
export function requireUser(event: any) {
const user = getSessionUser(event);
if (!user) {
throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
}
return user;
}
+667
View File
@@ -0,0 +1,667 @@
import { open, stat } from 'node:fs/promises';
import { basename } from 'node:path';
export interface ParsedMetadata {
title: string;
artist: string | null;
trackerFormat: string | null;
channels: number | null;
trackerName: string | null;
message: string | null;
instruments: string[] | null;
metadata: Record<string, any>;
}
// 辅助函数:清理二进制字符串,去除尾部空字符、空白及不可见字符
function cleanString(buffer: Buffer): string {
let str = buffer.toString('utf8');
str = str.replace(/\0+$/, '').trim();
str = str.replace(/[\x00-\x1F\x7F-\x9F]/g, '');
return str;
}
interface Reader {
read(offset: number, length: number): Buffer;
readUInt8(offset: number): number;
readUInt16LE(offset: number): number;
readUInt32LE(offset: number): number;
}
function createSyncReader(scanBuf: Buffer, fileLength: number): Reader {
const bufSize = scanBuf.length;
const read = (offset: number, length: number): Buffer => {
if (offset >= bufSize) {
return Buffer.alloc(0);
}
const realLength = Math.min(length, bufSize - offset);
if (realLength <= 0) {
return Buffer.alloc(0);
}
return scanBuf.subarray(offset, offset + realLength);
};
return {
read,
readUInt8(offset: number): number {
const b = read(offset, 1);
return b.length >= 1 ? b.readUInt8(0) : 0;
},
readUInt16LE(offset: number): number {
const b = read(offset, 2);
return b.length >= 2 ? b.readUInt16LE(0) : 0;
},
readUInt32LE(offset: number): number {
const b = read(offset, 4);
return b.length >= 4 ? b.readUInt32LE(0) : 0;
}
};
}
// 针对不同格式的解析函数
function parseXm(reader: Reader, fileLength: number): ParsedMetadata {
// 17-36字节为 Song Name
const titleBuf = reader.read(17, 20);
const title = cleanString(titleBuf);
// 37-56字节为 Tracker Name
const trackerNameBuf = reader.read(37, 20);
const trackerName = cleanString(trackerNameBuf);
// 68-69字节为 Channels
const channels = reader.readUInt16LE(68);
const numPatterns = reader.readUInt16LE(70);
const numInstruments = reader.readUInt16LE(72);
const headerSize = reader.readUInt32LE(60);
const instruments: string[] = [];
let message: string | null = null;
try {
let offset = 60 + headerSize;
// 1. 跳过所有 patterns
for (let p = 0; p < numPatterns; p++) {
if (offset + 9 > fileLength) break;
const patHeaderLen = reader.readUInt32LE(offset);
const patDataSize = reader.readUInt16LE(offset + 7);
offset += (patHeaderLen > 0 ? patHeaderLen : 9) + patDataSize;
}
// 2. 依次读取每个 Instrument Header 并提取 Name
for (let i = 0; i < numInstruments; i++) {
if (offset + 29 > fileLength) break;
const insSize = reader.readUInt32LE(offset);
const nameBuf = reader.read(offset + 4, 22);
const name = cleanString(nameBuf);
const numSamples = reader.readUInt16LE(offset + 27);
if (name) {
instruments.push(name);
}
// 精准计算并跳过这个 Instrument(含所有 sample headers 和 sample data)
let nextOffset = offset + insSize;
if (numSamples > 0 && insSize > 29) {
const sampleHeaderSize = reader.readUInt32LE(offset + 29);
let totalSampleDataSize = 0;
for (let s = 0; s < numSamples; s++) {
const shOffset = offset + insSize + s * sampleHeaderSize;
if (shOffset + 4 <= fileLength) {
const sampleLength = reader.readUInt32LE(shOffset);
totalSampleDataSize += sampleLength;
}
}
nextOffset = offset + insSize + numSamples * sampleHeaderSize + totalSampleDataSize;
}
offset = nextOffset > offset ? nextOffset : offset + 29;
}
// 3. 提取尾部 OpenMPT 扩展 Chunks (如 text, CMSG, CNAM, INAM)
while (offset + 8 <= fileLength) {
const tagBuf = reader.read(offset, 4);
if (tagBuf.length < 4) break;
const tag = tagBuf.toString('ascii');
// 校验 tag 是否是合法的 4 字符 ASCII(通常为大写字母,或者是 'text')
if (!/^[A-Z0-9]{4}$/.test(tag) && tag !== 'text') {
offset++;
continue;
}
const len = reader.readUInt32LE(offset + 4);
if (offset + 8 + len > fileLength || len < 0 || len > 1048576) {
offset++;
continue;
}
const chunkData = reader.read(offset + 8, len);
if (tag === 'text' || tag === 'CMSG') {
const msg = cleanString(chunkData);
if (msg) {
message = msg;
}
}
offset += 8 + len;
}
} catch (e) {
console.error('Failed to parse XM instruments', e);
}
return {
title,
artist: null,
trackerFormat: 'XM',
channels,
trackerName,
message,
instruments,
metadata: {}
};
}
function parseMod(reader: Reader, fileLength: number): ParsedMetadata {
const titleBuf = reader.read(0, 20);
const title = cleanString(titleBuf);
let signature = '';
if (fileLength >= 1084) {
const sigBuf = reader.read(1080, 4);
signature = sigBuf.toString('ascii');
}
let channels = 4;
if (['M.K.', 'M!K!', '4CHN', 'FLT4'].includes(signature)) {
channels = 4;
} else if (signature === '6CHN') {
channels = 6;
} else if (['8CHN', 'FLT8'].includes(signature)) {
channels = 8;
} else if (signature.endsWith('CHN')) {
const ch = parseInt(signature.substring(0, signature.length - 3), 10);
if (!isNaN(ch)) channels = ch;
} else if (signature.endsWith('CH')) {
const ch = parseInt(signature.substring(0, signature.length - 2), 10);
if (!isNaN(ch)) channels = ch;
}
const instruments: string[] = [];
try {
for (let i = 0; i < 31; i++) {
const offset = 20 + i * 30;
if (offset + 22 > fileLength) break;
const nameBuf = reader.read(offset, 22);
const name = cleanString(nameBuf);
if (name) {
instruments.push(name);
}
}
} catch (e) {
console.error('Failed to parse MOD instruments', e);
}
return {
title,
artist: null,
trackerFormat: 'MOD',
channels,
trackerName: null,
message: null,
instruments,
metadata: { signature }
};
}
async function parseIt(reader: Reader, fileLength: number): Promise<ParsedMetadata> {
const titleBuf = reader.read(4, 26);
const title = cleanString(titleBuf);
const channels = fileLength >= 33 ? reader.readUInt8(32) : 0;
const insNum = fileLength >= 36 ? reader.readUInt16LE(34) : 0;
const smpNum = fileLength >= 38 ? reader.readUInt16LE(36) : 0;
const itOrdNum = fileLength >= 34 ? reader.readUInt16LE(32) : 0;
// 提取 Song Message (留言)
let message: string | null = null;
try {
if (fileLength >= 60) {
const special = reader.readUInt16LE(0x2c);
if (special & 1) {
const msgLength = reader.readUInt16LE(0x36);
const msgOffset = reader.readUInt32LE(0x38);
if (msgOffset > 0 && msgLength > 0 && msgOffset + msgLength <= fileLength) {
const msgBuf = reader.read(msgOffset, msgLength);
message = cleanString(msgBuf);
}
}
}
} catch (e) {
console.error('Failed to parse IT song message', e);
}
const instruments: string[] = [];
try {
const insPtrOffset = 192 + itOrdNum;
const smpPtrOffset = insPtrOffset + insNum * 4;
if (insNum > 0) {
for (let i = 0; i < insNum; i++) {
const ptrIdx = insPtrOffset + i * 4;
if (ptrIdx + 4 > fileLength) break;
const offset = reader.readUInt32LE(ptrIdx);
if (offset > 0 && offset + 64 <= fileLength) {
const nameBuf = reader.read(offset + 32, 32);
const name = cleanString(nameBuf);
if (name) instruments.push(name);
}
}
}
for (let i = 0; i < smpNum; i++) {
const ptrIdx = smpPtrOffset + i * 4;
if (ptrIdx + 4 > fileLength) break;
const offset = reader.readUInt32LE(ptrIdx);
if (offset > 0 && offset + 52 <= fileLength) {
const nameBuf = reader.read(offset + 20, 32);
const name = cleanString(nameBuf);
if (name && !instruments.includes(name)) {
instruments.push(name);
}
}
}
} catch (e) {
console.error('Failed to parse IT instruments', e);
}
return {
title,
artist: null,
trackerFormat: 'IT',
channels,
trackerName: 'Impulse Tracker',
message,
instruments,
metadata: {}
};
}
function parseS3m(reader: Reader, fileLength: number): ParsedMetadata {
const titleBuf = reader.read(0, 28);
const title = cleanString(titleBuf);
let signature = '';
if (fileLength >= 48) {
const sigBuf = reader.read(44, 4);
signature = sigBuf.toString('ascii');
}
const insNum = fileLength >= 36 ? reader.readUInt16LE(34) : 0;
const ordNum = fileLength >= 34 ? reader.readUInt16LE(32) : 0;
const instruments: string[] = [];
try {
const insPtrOffset = 96 + ordNum;
for (let i = 0; i < insNum; i++) {
const ptrIdx = insPtrOffset + i * 2;
if (ptrIdx + 2 > fileLength) break;
const parapointer = reader.readUInt16LE(ptrIdx);
const realOffset = parapointer * 16;
if (realOffset > 0 && realOffset + 76 <= fileLength) {
const nameBuf = reader.read(realOffset + 48, 28);
const name = cleanString(nameBuf);
if (name) instruments.push(name);
}
}
} catch (e) {
console.error('Failed to parse S3M instruments', e);
}
return {
title,
artist: null,
trackerFormat: 'S3M',
channels: null,
trackerName: signature === 'SCRM' ? 'Scream Tracker 3' : null,
message: null,
instruments,
metadata: { signature }
};
}
// 提取 MP3 元数据 (ID3v1 和 ID3v2 标题/注释简易解析)
async function parseMp3(fd: any, fileLength: number): Promise<ParsedMetadata> {
let title = '';
let artist = '';
let message: string | null = null;
const metadata: Record<string, any> = {};
const headerSize = Math.min(8192, fileLength);
if (headerSize > 10) {
const header = Buffer.alloc(headerSize);
await fd.read(header, 0, headerSize, 0);
if (header.subarray(0, 3).toString('ascii') === 'ID3') {
metadata.hasId3v2 = true;
// 1. 查找标题 TIT2 帧
const tit2Idx = header.indexOf('TIT2');
if (tit2Idx !== -1 && tit2Idx + 10 < headerSize) {
const frameSize = header.readUInt32BE(tit2Idx + 4);
const encoding = header.readUInt8(tit2Idx + 10);
const textStart = tit2Idx + 11;
if (textStart + frameSize - 1 <= headerSize && frameSize > 1) {
const textBuf = header.subarray(textStart, textStart + frameSize - 1);
if (encoding === 0) {
title = cleanString(textBuf);
} else if (encoding === 1 || encoding === 2) {
title = textBuf.toString('utf16le');
title = title.replace(/^\ufeff/, '').replace(/\0+$/, '').trim();
} else if (encoding === 3) {
title = cleanString(textBuf);
}
}
}
// 2. 查找作者 TPE1 帧
const tpe1Idx = header.indexOf('TPE1');
if (tpe1Idx !== -1 && tpe1Idx + 10 < headerSize) {
const frameSize = header.readUInt32BE(tpe1Idx + 4);
const encoding = header.readUInt8(tpe1Idx + 10);
const textStart = tpe1Idx + 11;
if (textStart + frameSize - 1 <= headerSize && frameSize > 1) {
const textBuf = header.subarray(textStart, textStart + frameSize - 1);
if (encoding === 0) {
artist = cleanString(textBuf);
} else if (encoding === 1 || encoding === 2) {
artist = textBuf.toString('utf16le');
artist = artist.replace(/^\ufeff/, '').replace(/\0+$/, '').trim();
} else if (encoding === 3) {
artist = cleanString(textBuf);
}
}
}
// 3. 查找留言 COMM 帧
const commIdx = header.indexOf('COMM');
if (commIdx !== -1 && commIdx + 10 < headerSize) {
const frameSize = header.readUInt32BE(commIdx + 4);
const encoding = header.readUInt8(commIdx + 10);
const textStart = commIdx + 11;
if (textStart + frameSize - 1 <= headerSize && frameSize > 4) {
const textBuf = header.subarray(textStart + 3, textStart + frameSize - 1);
let actualStart = 0;
if (encoding === 0 || encoding === 3) {
const descEnd = textBuf.indexOf(0);
if (descEnd !== -1) actualStart = descEnd + 1;
message = cleanString(textBuf.subarray(actualStart));
} else {
let descEnd = -1;
for (let j = 0; j < textBuf.length - 1; j += 2) {
if (textBuf[j] === 0 && textBuf[j+1] === 0) {
descEnd = j;
break;
}
}
if (descEnd !== -1) actualStart = descEnd + 2;
message = textBuf.subarray(actualStart).toString('utf16le');
message = message.replace(/^\ufeff/, '').replace(/\0+$/, '').trim();
}
}
}
}
}
if (fileLength > 128) {
const footer = Buffer.alloc(128);
await fd.read(footer, 0, 128, fileLength - 128);
if (footer.subarray(0, 3).toString('ascii') === 'TAG') {
metadata.hasId3v1 = true;
if (!title) {
const titleBuf = footer.subarray(3, 33);
title = cleanString(titleBuf);
}
const artistBuf = footer.subarray(33, 63);
const artistV1 = cleanString(artistBuf);
if (artistV1) {
metadata.artist = artistV1;
if (!artist) {
artist = artistV1;
}
}
// ID3v1 留言在偏移 97 到 126
if (!message) {
const commentBuf = footer.subarray(97, 127);
message = cleanString(commentBuf);
}
}
}
return {
title,
artist: artist || null,
trackerFormat: 'MP3',
channels: null,
trackerName: null,
message,
instruments: null,
metadata
};
}
// 提取 OGG/FLAC/WAV 元数据 (检索前 8KB)
async function parseGenericAudio(fd: any, fileLength: number, format: string): Promise<ParsedMetadata> {
let title = '';
let artist = '';
let message: string | null = null;
const scanSize = Math.min(8192, fileLength);
if (scanSize > 10) {
const buf = Buffer.alloc(scanSize);
await fd.read(buf, 0, scanSize, 0);
// 1. WAV INFO List INAM / IART / ICMT 查找
if (format === 'WAV') {
const inamIdx = buf.indexOf('INAM');
if (inamIdx !== -1 && inamIdx + 8 < scanSize) {
const size = buf.readUInt32LE(inamIdx + 4);
if (inamIdx + 8 + size <= scanSize && size > 0) {
title = cleanString(buf.subarray(inamIdx + 8, inamIdx + 8 + size));
}
}
const iartIdx = buf.indexOf('IART');
if (iartIdx !== -1 && iartIdx + 8 < scanSize) {
const size = buf.readUInt32LE(iartIdx + 4);
if (iartIdx + 8 + size <= scanSize && size > 0) {
artist = cleanString(buf.subarray(iartIdx + 8, iartIdx + 8 + size));
}
}
const icmtIdx = buf.indexOf('ICMT');
if (icmtIdx !== -1 && icmtIdx + 8 < scanSize) {
const size = buf.readUInt32LE(icmtIdx + 4);
if (icmtIdx + 8 + size <= scanSize && size > 0) {
message = cleanString(buf.subarray(icmtIdx + 8, icmtIdx + 8 + size));
}
}
}
// 2. OGG/FLAC Vorbis Comment TITLE / ARTIST / COMMENT / DESCRIPTION 查找
if (['OGG', 'FLAC'].includes(format)) {
// 2.1 查找标题
let titleIdx = buf.indexOf('TITLE=');
if (titleIdx === -1) {
titleIdx = buf.indexOf('title=');
}
if (titleIdx !== -1 && titleIdx + 6 < scanSize) {
const textBuf = buf.subarray(titleIdx + 6);
let endIdx = 0;
while (endIdx < textBuf.length) {
const charCode = textBuf[endIdx];
if (charCode === undefined || charCode < 32 || charCode >= 127) {
break;
}
endIdx++;
}
title = cleanString(textBuf.subarray(0, endIdx));
}
// 2.2 查找作者
let artistIdx = buf.indexOf('ARTIST=');
let prefixLen = 7;
if (artistIdx === -1) {
artistIdx = buf.indexOf('artist=');
prefixLen = 7;
}
if (artistIdx === -1) {
artistIdx = buf.indexOf('PERFORMER=');
prefixLen = 10;
}
if (artistIdx === -1) {
artistIdx = buf.indexOf('performer=');
prefixLen = 10;
}
if (artistIdx !== -1 && artistIdx + prefixLen < scanSize) {
const textBuf = buf.subarray(artistIdx + prefixLen);
let endIdx = 0;
while (endIdx < textBuf.length) {
const charCode = textBuf[endIdx];
if (charCode === undefined || charCode < 32 || charCode >= 127) {
break;
}
endIdx++;
}
artist = cleanString(textBuf.subarray(0, endIdx));
}
// 2.3 查找留言 (COMMENT 或 DESCRIPTION)
let commIdx = buf.indexOf('COMMENT=');
let commPrefix = 8;
if (commIdx === -1) {
commIdx = buf.indexOf('comment=');
commPrefix = 8;
}
if (commIdx === -1) {
commIdx = buf.indexOf('DESCRIPTION=');
commPrefix = 12;
}
if (commIdx === -1) {
commIdx = buf.indexOf('description=');
commPrefix = 12;
}
if (commIdx !== -1 && commIdx + commPrefix < scanSize) {
const textBuf = buf.subarray(commIdx + commPrefix);
let endIdx = 0;
while (endIdx < textBuf.length) {
const charCode = textBuf[endIdx];
if (charCode === undefined || charCode < 32 || charCode >= 127) {
break;
}
endIdx++;
}
message = cleanString(textBuf.subarray(0, endIdx));
}
}
}
return {
title,
artist: artist || null,
trackerFormat: format,
channels: null,
trackerName: null,
message,
instruments: null,
metadata: {}
};
}
// 主入口函数
export async function parseMetadata(filePath: string, ext: string): Promise<ParsedMetadata> {
const upperExt = ext.toUpperCase();
let fd: any = null;
try {
const fileStats = await stat(filePath);
const fileLength = fileStats.size;
fd = await open(filePath, 'r');
let result: ParsedMetadata;
// 对于 Tracker 音乐,直接预读前 2MB 并在内存中进行高速同步解析,解决超大文件截断问题
if (['XM', 'MOD', 'IT', 'S3M'].includes(upperExt)) {
const scanBufSize = Math.min(2097152, fileLength);
const scanBuf = Buffer.alloc(scanBufSize);
await fd.read(scanBuf, 0, scanBufSize, 0);
const reader = createSyncReader(scanBuf, fileLength);
switch (upperExt) {
case 'XM':
result = parseXm(reader, fileLength);
break;
case 'MOD':
result = parseMod(reader, fileLength);
break;
case 'IT':
result = await parseIt(reader, fileLength);
break;
case 'S3M':
result = parseS3m(reader, fileLength);
break;
default:
throw new Error('Unsupported tracker type');
}
} else {
// 其它非 Tracker 音频格式,依然采用各自的异步解析
switch (upperExt) {
case 'MP3':
result = await parseMp3(fd, fileLength);
break;
case 'OGG':
case 'FLAC':
case 'WAV':
result = await parseGenericAudio(fd, fileLength, upperExt);
break;
default:
result = {
title: '',
artist: null,
trackerFormat: upperExt,
channels: null,
trackerName: null,
message: null,
instruments: null,
metadata: {}
};
}
}
if (!result.title) {
const name = basename(filePath);
const dotIdx = name.lastIndexOf('.');
result.title = dotIdx !== -1 ? name.substring(0, dotIdx) : name;
}
return result;
} catch (error) {
const name = basename(filePath);
const dotIdx = name.lastIndexOf('.');
return {
title: dotIdx !== -1 ? name.substring(0, dotIdx) : name,
artist: null,
trackerFormat: upperExt,
channels: null,
trackerName: null,
message: null,
instruments: null,
metadata: { error: String(error) }
};
} finally {
if (fd) {
await fd.close();
}
}
}
+116
View File
@@ -0,0 +1,116 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
export interface SongEntry {
id: number;
fileName: string;
}
const PLAYLIST_PATH = join(
process.cwd(),
"public",
"json",
"playlist_xm_mod_pressed.json",
);
let cachedRaw: unknown[] | null = null;
let cachedSorted: string[] | null = null;
async function loadPlaylistRaw(): Promise<unknown[] | null> {
if (cachedRaw) {
return cachedRaw;
}
try {
const rawText = await readFile(PLAYLIST_PATH, "utf8");
const parsed = JSON.parse(rawText);
if (Array.isArray(parsed)) {
cachedRaw = parsed;
return parsed;
}
} catch (error) {
return null;
}
return null;
}
function extractFileNamesFromJsonh(raw: unknown[]): string[] {
if (!Array.isArray(raw) || raw.length < 2) return [];
const keyCount = Number(raw[0]);
if (!Number.isInteger(keyCount) || keyCount <= 0) return [];
if (raw.length < 1 + keyCount) return [];
const keys = raw.slice(1, 1 + keyCount);
const fnIndex = keys.findIndex((key) => key === "fn");
if (fnIndex === -1) return [];
const valuesStart = 1 + keyCount;
const total = Math.floor((raw.length - valuesStart) / keyCount);
const names: string[] = [];
for (let i = 0; i < total; i += 1) {
const value = raw[valuesStart + i * keyCount + fnIndex];
if (typeof value === "string") {
const trimmed = value.trim();
if (trimmed) names.push(trimmed);
}
}
return names;
}
function extractFileNamesFromPlain(raw: unknown[]): string[] {
const names: string[] = [];
for (const entry of raw) {
if (typeof entry === "string") {
const trimmed = entry.trim();
if (trimmed) names.push(trimmed);
continue;
}
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const fn = (entry as { fn?: unknown }).fn;
if (typeof fn === "string") {
const trimmed = fn.trim();
if (trimmed) names.push(trimmed);
}
}
return names;
}
async function loadSortedPlaylist(): Promise<string[] | null> {
if (cachedSorted) return cachedSorted;
const raw = await loadPlaylistRaw();
if (!raw) return null;
const jsonhNames = extractFileNamesFromJsonh(raw);
const names = jsonhNames.length ? jsonhNames : extractFileNamesFromPlain(raw);
if (!names.length) return null;
names.sort((a, b) => {
const fnA = a.toUpperCase();
const fnB = b.toUpperCase();
if (fnA < fnB) return -1;
if (fnA > fnB) return 1;
return 0;
});
cachedSorted = names;
return names;
}
export async function getSongById(id: number): Promise<SongEntry | null> {
if (!Number.isInteger(id) || id < 1) {
return null;
}
const playlist = await loadSortedPlaylist();
if (!playlist) return null;
const fileName = playlist[id - 1];
if (typeof fileName !== "string" || !fileName) return null;
return {
id,
fileName,
};
}
+262
View File
@@ -0,0 +1,262 @@
import { readdir, stat } from 'node:fs/promises';
import { join } from 'node:path';
import db from '../db';
import { parseMetadata } from './metadata-parser';
// 音乐文件夹的基础路径(优先从环境变量读取,默认指向本地 data/music 目录)
const MUSIC_BASE_PATH = process.env.MUSIC_PATH || join(process.cwd(), 'data/music');
// 支持的前端可播放扩展名
// 所有可播放格式:
// - Tracker 模块(Chiptune3/libopenmpt 原生支持)
// - 现代音频(浏览器原生 <audio> 播放)
// - FFmpeg 可转换格式(引擎3 转 MP3 播放)
const PLAYABLE_EXTENSIONS = new Set([
// Tracker: BassoonTracker + Chiptune3
'mod', 'xm',
// Tracker: Chiptune3 (libopenmpt)
'it', 's3m', 'umx', 'mptm', 'stm', 'mtm', 'ptm', 'far', 'ult', '669',
'amf', 'dsm', 'mdl', 'med', 'okt', 'psm', 'dbm', 'imf', 'j2b', 'mo3',
'gdm', 'stp', 'sfx', 'sfx2', 'itp', 'dtm', 'mt2', 'symmod', 'c67', 'ams', 'stx',
'667', 'cba', 'digi', 'dmf', 'dsym', 'etx', 'fc', 'fc13', 'fc14', 'fmt', 'ftm',
'gmc', 'gt2', 'gtk', 'ice', 'ims', 'm15', 'mms', 'mus', 'oxm', 'plm', 'pt36',
'puma', 'rtm', 'smod', 'st26', 'stk', 'wow', 'xmf', 'mdz', 's3z', 'xmz', 'itz',
'mptmz', 'mdr',
// 现代音频:浏览器原生 <audio>
'ogg', 'mp3', 'wav', 'flac',
// FFmpeg 可转换通用音频格式(引擎3)
'aac', 'opus', 'aiff', 'm4a', 'wma', 'ac3', 'dts',
'ape', 'wv', 'tta', 'mp2', 'amr', 'ra', 'au', 'voc', 'pcm',
'spx', 'tak', 'cda', 'adpcm', 'gsm', 'vqf', 'ofr', 'mp1',
]);
export interface ScanStatus {
isScanning: boolean;
totalFiles: number;
processedFiles: number;
addedCount: number;
updatedCount: number;
deletedCount: number;
skippedCount: number;
startTime: number | null;
endTime: number | null;
error: string | null;
}
let currentStatus: ScanStatus = {
isScanning: false,
totalFiles: 0,
processedFiles: 0,
addedCount: 0,
updatedCount: 0,
deletedCount: 0,
skippedCount: 0,
startTime: null,
endTime: null,
error: null
};
// 后台异步执行扫描
export async function runScanAsync(forceRefresh = false) {
if (currentStatus.isScanning) return;
currentStatus = {
isScanning: true,
totalFiles: 0,
processedFiles: 0,
addedCount: 0,
updatedCount: 0,
deletedCount: 0,
skippedCount: 0,
startTime: Date.now(),
endTime: null,
error: null
};
try {
// 1. 读取目录下的所有文件
const files = await readdir(MUSIC_BASE_PATH);
currentStatus.totalFiles = files.length;
// 2. 从数据库中拉取所有已存在的歌曲信息,进行增量比对
const existingSongs = db.prepare('SELECT filename, file_size, file_mtime FROM songs').all() as Array<{
filename: string;
file_size: number;
file_mtime: number;
}>;
const existingMap = new Map<string, { file_size: number; file_mtime: number }>();
for (const song of existingSongs) {
existingMap.set(song.filename, {
file_size: song.file_size,
file_mtime: song.file_mtime
});
}
const currentFilesSet = new Set(files);
// 3. 处理删除的文件
const toDelete: string[] = [];
for (const filename of existingMap.keys()) {
if (!currentFilesSet.has(filename)) {
toDelete.push(filename);
}
}
if (toDelete.length > 0) {
const deleteStmt = db.prepare('DELETE FROM songs WHERE filename = ?');
const deleteTx = db.transaction((names: string[]) => {
for (const name of names) {
deleteStmt.run(name);
}
});
deleteTx(toDelete);
currentStatus.deletedCount = toDelete.length;
}
// 4. 并发读取新文件或修改过的文件并批量写入 SQLite
const concurrency = 100;
const batchSize = 1000;
let batch: any[] = [];
const insertStmt = db.prepare(`
INSERT INTO songs (filename, title, artist, extension, file_size, file_mtime, playable, tracker_format, channels, tracker_name, message, instruments, metadata)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const updateStmt = db.prepare(`
UPDATE songs SET title = ?, artist = ?, file_size = ?, file_mtime = ?, playable = ?, tracker_format = ?, channels = ?, tracker_name = ?, message = ?, instruments = ?, metadata = ?
WHERE filename = ?
`);
// 批量提交事务
const commitBatch = db.transaction((items: any[]) => {
for (const item of items) {
if (item.action === 'insert') {
insertStmt.run(
item.filename,
item.title,
item.artist,
item.extension,
item.file_size,
item.file_mtime,
item.playable,
item.tracker_format,
item.channels,
item.tracker_name,
item.message,
item.instruments,
item.metadata
);
} else if (item.action === 'update') {
updateStmt.run(
item.title,
item.artist,
item.file_size,
item.file_mtime,
item.playable,
item.tracker_format,
item.channels,
item.tracker_name,
item.message,
item.instruments,
item.metadata,
item.filename
);
}
}
});
// 线程池队列处理
let index = 0;
const workers = Array(concurrency).fill(null).map(async () => {
while (index < files.length) {
const i = index++;
if (i >= files.length) break;
const filename = files[i];
if (!filename) continue;
const filePath = join(MUSIC_BASE_PATH, filename);
try {
const stats = await stat(filePath);
const size = stats.size;
const mtime = stats.mtimeMs;
const existing = existingMap.get(filename);
if (!forceRefresh && existing && existing.file_size === size && Math.abs(existing.file_mtime - mtime) < 1000) {
// 文件未发生变化,跳过
currentStatus.skippedCount++;
continue;
}
// 文件新增或修改
const ext = filename.split('.').pop()?.toLowerCase() || '';
const playable = PLAYABLE_EXTENSIONS.has(ext) ? 1 : 0;
const meta = await parseMetadata(filePath, ext);
const item = {
action: existing ? 'update' : 'insert',
filename,
title: meta.title,
artist: meta.artist,
extension: ext,
file_size: size,
file_mtime: mtime,
playable,
tracker_format: meta.trackerFormat,
channels: meta.channels,
tracker_name: meta.trackerName,
message: meta.message,
instruments: meta.instruments ? JSON.stringify(meta.instruments) : null,
metadata: JSON.stringify(meta.metadata)
};
batch.push(item);
if (batch.length >= batchSize) {
const currentBatch = batch;
batch = [];
commitBatch(currentBatch);
const updates = currentBatch.filter(x => x.action === 'update').length;
const inserts = currentBatch.filter(x => x.action === 'insert').length;
currentStatus.updatedCount += updates;
currentStatus.addedCount += inserts;
}
} catch (e) {
console.error(`Error scanning file ${filename}:`, e);
} finally {
currentStatus.processedFiles++;
}
}
});
await Promise.all(workers);
// 提交剩下的批次
if (batch.length > 0) {
commitBatch(batch);
currentStatus.updatedCount += batch.filter(x => x.action === 'update').length;
currentStatus.addedCount += batch.filter(x => x.action === 'insert').length;
}
currentStatus.endTime = Date.now();
} catch (error: any) {
currentStatus.error = error.message || String(error);
console.error('Scan failed:', error);
} finally {
currentStatus.isScanning = false;
}
}
export function getScanStatus(): ScanStatus {
return currentStatus;
}
export function startScan(forceRefresh = false) {
if (currentStatus.isScanning) return;
// 后台异步执行
runScanAsync(forceRefresh);
}