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
};
});