feat: 迁移架构&实现功能

- 持久化音量设置
- 搜索页支持自定义每页显示数量(持久化)
- vite-electron-plugin迁移electron-vite
This commit is contained in:
lqtmcstudio
2026-02-06 14:50:33 +08:00
parent 6cda900c8d
commit d6e1d11a52
37 changed files with 867 additions and 1732 deletions

View File

@@ -2,6 +2,7 @@ import { app } from 'electron'
import path from 'path'
import fs from 'fs'
import { createRequire } from 'node:module'
import { MessagePlugin } from "tdesign-vue-next";
const require = createRequire(import.meta.url)
@@ -15,7 +16,8 @@ type PluginModule = {
getUrl?: (id: string, quality: string) => Promise<string> | string,
musicSearch?: {
search: (query: string, page: number, limit: number) => Promise<any> | any
}
},
getLyric?: (id: string) => Promise<string> | object
}
export class PluginSystem {
@@ -26,27 +28,6 @@ export class PluginSystem {
this.loadPlugin()
}
async search(query: string, page: number, limit: number): Promise<any> {
if (!this.plugin?.musicSearch?.search) {
return {
list: [],
total: 0,
allPage: 0,
error: 'Search not implemented'
}
}
try {
return await this.plugin.musicSearch.search(query, page, limit)
} catch (e: any) {
return {
list: [],
total: 0,
allPage: 0,
error: e.message || 'Plugin search error'
}
}
}
private loadPlugin() {
try {
const pluginPath = path.join(
@@ -100,4 +81,42 @@ export class PluginSystem {
}
}
}
async search(query: string, page: number, limit: number): Promise<any> {
if (!this.plugin?.musicSearch?.search) {
return {
list: [],
total: 0,
allPage: 0,
error: 'Search not implemented'
}
}
try {
return await this.plugin.musicSearch.search(query, page, limit)
} catch (e: any) {
return {
list: [],
total: 0,
allPage: 0,
error: e.message || 'Plugin search error'
}
}
}
async getLyric(id: string): Promise<any> {
console.log("getLyric not implemented");
if (!this.plugin?.getLyric) {
console.log("getLyric not implemented2");
return
}
try {
const result = await this.plugin.getLyric(id)
console.log(result)
return result
} catch (e: any) {
console.log(e)
MessagePlugin.error(e).then()
return {}
}
}
}

974
src/main/proxyServer.ts Normal file
View File

@@ -0,0 +1,974 @@
import http from 'http';
import { Readable } from 'stream';
import fs from 'fs';
import path from 'path';
import { app } from 'electron';
// @ts-ignore
import { PluginSystem } from './pluginSystem.ts';
const PORT = 5266;
let CACHE_DIR = '';
function ensureCacheDir() {
if (!CACHE_DIR) {
CACHE_DIR = path.join(app.getPath('userData'), 'music', 'cache');
}
if (!fs.existsSync(CACHE_DIR)) {
try {
fs.mkdirSync(CACHE_DIR, { recursive: true });
console.log(`[Proxy] Created cache directory: ${CACHE_DIR}`);
} catch (e) {
console.error('[Proxy] Failed to create cache directory:', e);
}
}
return CACHE_DIR;
}
interface CacheEntry {
url: string;
expiresAt: number;
}
interface CacheMetadata {
totalSize: number;
contentType: string;
complete: boolean;
createdAt: number;
}
interface DownloadTask {
currentSize: number;
totalSize: number;
contentType: string;
abortController: AbortController | null;
promise: Promise<void> | null;
// 新增:用于通知等待者的回调列表
waiters: Array<{ start: number; end: number; resolve: () => void; reject: (err: Error) => void }>;
}
// Memory cache for resolved URLs
const urlCache = new Map<string, CacheEntry>();
// Track background download tasks
const downloadTasks = new Map<string, DownloadTask>();
function getCachePath(source: string, id: string, quality: string) {
const dir = ensureCacheDir();
const safeId = id.replace(/[^a-z0-9]/gi, '_');
return path.join(dir, `${source}-${safeId}-${quality}`);
}
function getMetadataPath(cachePath: string): string {
return cachePath + '.meta';
}
function getTempPath(cachePath: string): string {
return cachePath + '.tmp';
}
function readMetadata(cachePath: string): CacheMetadata | null {
const metaPath = getMetadataPath(cachePath);
try {
if (fs.existsSync(metaPath)) {
return JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
}
} catch (e) {
console.error('[Proxy] Failed to read metadata:', e);
}
return null;
}
function writeMetadata(cachePath: string, metadata: CacheMetadata) {
const metaPath = getMetadataPath(cachePath);
try {
fs.writeFileSync(metaPath, JSON.stringify(metadata));
} catch (e) {
console.error('[Proxy] Failed to write metadata:', e);
}
}
async function fetchFreshUrl(source: string, id: string, quality: string): Promise<string | null> {
try {
const plugin = new PluginSystem(source);
const result = await plugin.getUrl(id, quality);
if (result.success && result.url) {
urlCache.set(`${source}:${id}:${quality}`, {
url: result.url,
expiresAt: Date.now() + 3600 * 1000
});
return result.url;
}
console.error(`[Proxy] Failed to fetch URL for ${source}:${id}`, result.error);
return null;
} catch (e) {
console.error(`[Proxy] Error fetching URL:`, e);
return null;
}
}
function isValidCacheFile(filePath: string): boolean {
try {
const metadata = readMetadata(filePath);
if (!metadata || !metadata.complete) return false;
if (!fs.existsSync(filePath)) return false;
const stat = fs.statSync(filePath);
return stat.size === metadata.totalSize && stat.size > 1024;
} catch {
return false;
}
}
function parseRangeHeader(range: string | undefined, fileSize: number): { start: number; end: number } | null {
if (!range) return null;
const match = range.match(/bytes=(\d*)-(\d*)/);
if (!match) return null;
let start = match[1] ? parseInt(match[1], 10) : 0;
let end = match[2] ? parseInt(match[2], 10) : fileSize - 1;
if (start >= fileSize) return null;
end = Math.min(end, fileSize - 1);
return { start, end };
}
function serveFromCache(req: http.IncomingMessage, res: http.ServerResponse, filePath: string): boolean {
try {
const metadata = readMetadata(filePath);
if (!metadata) {
console.warn('[Proxy] No metadata for cache file');
return false;
}
const stat = fs.statSync(filePath);
const fileSize = stat.size;
const range = parseRangeHeader(req.headers.range, fileSize);
if (range) {
const { start, end } = range;
const chunksize = (end - start) + 1;
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': metadata.contentType || 'audio/mpeg',
});
const file = fs.createReadStream(filePath, { start, end });
file.pipe(res);
file.on('error', (err) => {
console.error('[Proxy] Error reading cache file:', err);
if (!res.headersSent) {
res.writeHead(500);
res.end('Cache read error');
}
});
} else {
res.writeHead(200, {
'Content-Length': fileSize,
'Content-Type': metadata.contentType || 'audio/mpeg',
'Accept-Ranges': 'bytes',
});
const stream = fs.createReadStream(filePath);
stream.pipe(res);
stream.on('error', (err) => {
console.error('[Proxy] Error reading cache file:', err);
});
}
return true;
} catch (e) {
console.error('[Proxy] Error serving from cache:', e);
return false;
}
}
/**
* 直接代理 Range 请求,不缓存(用于 seek 到未下载的位置)
*/
async function proxyRangeDirect(
req: http.IncomingMessage,
res: http.ServerResponse,
targetUrl: string,
totalSize: number,
contentType: string
): Promise<void> {
const headers: Record<string, string> = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
};
if (req.headers.range) {
headers['Range'] = req.headers.range;
}
const response = await fetch(targetUrl, {
method: 'GET',
headers: headers,
});
if (!response.ok && response.status !== 206) {
throw { statusCode: response.status, statusText: response.statusText };
}
const responseContentType = response.headers.get('content-type') || contentType || 'audio/mpeg';
const contentLength = response.headers.get('content-length');
const contentRange = response.headers.get('content-range');
if (response.status === 206 && contentRange) {
res.writeHead(206, {
'Content-Type': responseContentType,
'Content-Length': contentLength || '',
'Content-Range': contentRange,
'Accept-Ranges': 'bytes',
});
} else {
res.writeHead(200, {
'Content-Type': responseContentType,
'Content-Length': contentLength || '',
'Accept-Ranges': 'bytes',
});
}
if (!response.body) {
res.end();
return;
}
// @ts-ignore
const nodeStream = Readable.fromWeb(response.body);
nodeStream.pipe(res);
return new Promise((resolve, reject) => {
nodeStream.on('end', resolve);
nodeStream.on('error', reject);
res.on('close', () => {
nodeStream.destroy();
resolve();
});
});
}
/**
* 从部分下载的缓存中读取已下载的部分
*/
function serveFromPartialCache(
req: http.IncomingMessage,
res: http.ServerResponse,
filePath: string,
task: DownloadTask
): boolean {
try {
const tempPath = getTempPath(filePath);
if (!fs.existsSync(tempPath)) return false;
const range = parseRangeHeader(req.headers.range, task.totalSize);
if (!range) return false;
const { start, end } = range;
// 检查请求的范围是否已下载,使用实际文件大小而不是 task.currentSize
// 因为文件写入可能有延迟
let actualSize: number;
try {
actualSize = fs.statSync(tempPath).size;
} catch {
return false;
}
// 确保请求的范围完全在已下载的部分内
if (end >= actualSize) {
return false;
}
const chunksize = (end - start) + 1;
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${task.totalSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': task.contentType || 'audio/mpeg',
});
const file = fs.createReadStream(tempPath, { start, end });
file.pipe(res);
file.on('error', (err) => {
console.error('[Proxy] Error reading partial cache:', err);
});
return true;
} catch (e) {
console.error('[Proxy] Error serving from partial cache:', e);
return false;
}
}
/**
* 启动后台下载任务(不阻塞当前请求)
* 修复版本:确保下载任务独立运行,不受客户端连接影响
*/
function startBackgroundDownload(
targetUrl: string,
cacheFilePath: string,
cacheKey: string
): DownloadTask {
const existingTask = downloadTasks.get(cacheFilePath);
if (existingTask && existingTask.promise) {
console.log(`[Proxy] Reusing existing download task for ${cacheFilePath}`);
return existingTask;
}
const abortController = new AbortController();
const task: DownloadTask = {
currentSize: 0,
totalSize: 0,
contentType: 'audio/mpeg',
abortController,
promise: null,
waiters: [],
};
downloadTasks.set(cacheFilePath, task);
task.promise = (async () => {
const tempPath = getTempPath(cacheFilePath);
try {
// 清理旧文件
try {
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
} catch { }
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
},
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const contentLength = parseInt(response.headers.get('content-length') || '0', 10);
const contentType = response.headers.get('content-type') || 'audio/mpeg';
if (!contentLength) {
console.warn('[Proxy] Background download: No content-length, skipping cache');
downloadTasks.delete(cacheFilePath);
return;
}
task.totalSize = contentLength;
task.contentType = contentType;
console.log(`[Proxy] Background download started: ${cacheFilePath} (${contentLength} bytes)`);
const fileStream = fs.createWriteStream(tempPath);
if (!response.body) {
downloadTasks.delete(cacheFilePath);
return;
}
// @ts-ignore
const nodeStream = Readable.fromWeb(response.body);
await new Promise<void>((resolve, reject) => {
nodeStream.on('data', (chunk: Buffer) => {
task.currentSize += chunk.length;
// 通知等待下载进度的请求
notifyWaiters(task);
// 每 10% 输出一次进度
if (task.currentSize % Math.floor(contentLength / 10) < chunk.length) {
const percent = Math.floor((task.currentSize / contentLength) * 100);
console.log(`[Proxy] Download progress: ${percent}% (${task.currentSize}/${contentLength})`);
}
});
nodeStream.pipe(fileStream);
fileStream.on('finish', () => {
try {
const stat = fs.statSync(tempPath);
if (stat.size === contentLength) {
fs.renameSync(tempPath, cacheFilePath);
writeMetadata(cacheFilePath, {
totalSize: contentLength,
contentType: contentType,
complete: true,
createdAt: Date.now()
});
console.log(`[Proxy] Background download complete: ${cacheFilePath}`);
} else {
console.warn(`[Proxy] Incomplete download: ${stat.size}/${contentLength}`);
try { fs.unlinkSync(tempPath); } catch { }
}
} catch (e) {
console.error('[Proxy] Failed to finalize cache:', e);
try { fs.unlinkSync(tempPath); } catch { }
}
resolve();
});
fileStream.on('error', (err) => {
console.error('[Proxy] Background download write error:', err);
try { fs.unlinkSync(tempPath); } catch { }
reject(err);
});
nodeStream.on('error', (err: Error) => {
console.error('[Proxy] Background download stream error:', err);
fileStream.destroy();
try { fs.unlinkSync(tempPath); } catch { }
reject(err);
});
});
} catch (e: any) {
if (e.name !== 'AbortError') {
console.error('[Proxy] Background download failed:', e);
}
try { fs.unlinkSync(tempPath); } catch { }
// 通知所有等待者下载失败
for (const waiter of task.waiters) {
waiter.reject(new Error('Download failed'));
}
task.waiters = [];
} finally {
downloadTasks.delete(cacheFilePath);
}
})();
return task;
}
/**
* 通知等待下载进度的请求
*/
function notifyWaiters(task: DownloadTask) {
const resolvedWaiters: number[] = [];
for (let i = 0; i < task.waiters.length; i++) {
const waiter = task.waiters[i];
// 当下载进度超过请求的结束位置时,通知等待者
if (task.currentSize > waiter.end) {
waiter.resolve();
resolvedWaiters.push(i);
}
}
// 移除已解决的等待者
for (let i = resolvedWaiters.length - 1; i >= 0; i--) {
task.waiters.splice(resolvedWaiters[i], 1);
}
}
/**
* 主代理函数 - 智能处理缓存和 Range 请求
* 修复版本:正确处理流的复制,确保下载和响应同时进行
*/
async function proxyAndCache(
req: http.IncomingMessage,
res: http.ServerResponse,
targetUrl: string,
cacheFilePath: string,
cacheKey: string
): Promise<void> {
const requestedRange = req.headers.range;
const isSeekRequest = requestedRange && !requestedRange.startsWith('bytes=0-');
// 检查是否有正在进行的后台下载
let task = downloadTasks.get(cacheFilePath);
if (task) {
console.log(`[Proxy] Download in progress: ${task.currentSize}/${task.totalSize}`);
if (requestedRange && task.totalSize > 0) {
const range = parseRangeHeader(requestedRange, task.totalSize);
if (range) {
// 获取临时文件的实际大小
const tempPath = getTempPath(cacheFilePath);
let actualSize = 0;
try {
if (fs.existsSync(tempPath)) {
actualSize = fs.statSync(tempPath).size;
}
} catch { }
// 如果请求的范围已经下载完成,从缓存读取
if (range.end < actualSize) {
console.log(`[Proxy] Serving range ${range.start}-${range.end} from partial cache (downloaded: ${actualSize})`);
if (serveFromPartialCache(req, res, cacheFilePath, task)) {
return;
}
}
// 请求的数据还没下载到,直接代理
console.log(`[Proxy] Range ${range.start}-${range.end} not cached yet (downloaded: ${actualSize}), proxying directly`);
await proxyRangeDirect(req, res, targetUrl, task.totalSize, task.contentType);
return;
}
}
// 无法确定如何处理,直接代理
await proxyRangeDirect(req, res, targetUrl, task.totalSize, task.contentType);
return;
}
// 没有正在进行的下载任务
if (isSeekRequest) {
// Seek 请求:启动后台下载任务,同时直接代理当前请求
console.log(`[Proxy] Seek request: ${requestedRange}, starting background download`);
// 启动后台下载(不等待)
startBackgroundDownload(targetUrl, cacheFilePath, cacheKey);
// 获取文件信息用于正确的 Range 响应
const headResponse = await fetch(targetUrl, {
method: 'HEAD',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
const totalSize = parseInt(headResponse.headers.get('content-length') || '0', 10);
const contentType = headResponse.headers.get('content-type') || 'audio/mpeg';
// 直接代理当前的 Range 请求
await proxyRangeDirect(req, res, targetUrl, totalSize, contentType);
return;
}
// 从头开始的请求:下载并同时流式返回
await streamAndCache(req, res, targetUrl, cacheFilePath, cacheKey);
}
/**
* 新增:边下载边返回给客户端,同时写入缓存
* 使用 PassThrough 流正确复制数据
*/
async function streamAndCache(
req: http.IncomingMessage,
res: http.ServerResponse,
targetUrl: string,
cacheFilePath: string,
cacheKey: string
): Promise<void> {
const headers: Record<string, string> = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
};
const response = await fetch(targetUrl, {
method: 'GET',
headers: headers,
});
if (!response.ok) {
throw { statusCode: response.status, statusText: response.statusText };
}
const contentLength = parseInt(response.headers.get('content-length') || '0', 10);
const contentType = response.headers.get('content-type') || 'audio/mpeg';
if (!contentLength) {
console.warn('[Proxy] No content-length, proxying without cache');
res.writeHead(200, {
'Content-Type': contentType,
'Accept-Ranges': 'bytes',
});
if (response.body) {
// @ts-ignore
const nodeStream = Readable.fromWeb(response.body);
nodeStream.pipe(res);
} else {
res.end();
}
return;
}
const tempPath = getTempPath(cacheFilePath);
// 清理旧文件
try {
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
if (fs.existsSync(cacheFilePath)) fs.unlinkSync(cacheFilePath);
} catch { }
const fileStream = fs.createWriteStream(tempPath);
// 创建下载任务用于跟踪进度
const task: DownloadTask = {
currentSize: 0,
totalSize: contentLength,
contentType: contentType,
abortController: null,
promise: null,
waiters: [],
};
downloadTasks.set(cacheFilePath, task);
console.log(`[Proxy] Starting stream download: ${cacheFilePath} (${contentLength} bytes)`);
// 发送响应头
res.writeHead(200, {
'Content-Length': contentLength,
'Content-Type': contentType,
'Accept-Ranges': 'bytes',
});
if (!response.body) {
res.end();
downloadTasks.delete(cacheFilePath);
return;
}
// @ts-ignore
const nodeStream = Readable.fromWeb(response.body);
// 关键修复:使用正确的方式将流复制到多个目标
// 手动读取数据并写入多个目标
let clientConnected = true;
let downloadComplete = false;
res.on('close', () => {
clientConnected = false;
console.log('[Proxy] Client disconnected');
});
return new Promise<void>((resolve, reject) => {
nodeStream.on('data', (chunk: Buffer) => {
task.currentSize += chunk.length;
// 写入文件(始终进行)
fileStream.write(chunk);
// 写入响应(如果客户端还连接着)
if (clientConnected && !res.writableEnded) {
res.write(chunk);
}
// 通知等待者
notifyWaiters(task);
});
nodeStream.on('end', () => {
downloadComplete = true;
// 结束文件流
fileStream.end();
// 结束响应(如果客户端还连接着)
if (clientConnected && !res.writableEnded) {
res.end();
}
});
nodeStream.on('error', (err: Error) => {
console.error('[Proxy] Stream error:', err);
fileStream.destroy();
if (clientConnected && !res.headersSent) {
res.writeHead(502);
res.end('Proxy stream error');
}
downloadTasks.delete(cacheFilePath);
try { fs.unlinkSync(tempPath); } catch { }
reject(err);
});
fileStream.on('finish', () => {
downloadTasks.delete(cacheFilePath);
// 验证并移动文件
try {
const stat = fs.statSync(tempPath);
if (stat.size === contentLength) {
fs.renameSync(tempPath, cacheFilePath);
writeMetadata(cacheFilePath, {
totalSize: contentLength,
contentType: contentType,
complete: true,
createdAt: Date.now()
});
console.log(`[Proxy] Cache complete: ${cacheFilePath} (${contentLength} bytes)`);
} else {
console.warn(`[Proxy] Incomplete download: ${stat.size}/${contentLength}`);
try { fs.unlinkSync(tempPath); } catch { }
}
} catch (e) {
console.error('[Proxy] Failed to finalize cache:', e);
try { fs.unlinkSync(tempPath); } catch { }
}
resolve();
});
fileStream.on('error', (err) => {
console.error('[Proxy] File write error:', err);
downloadTasks.delete(cacheFilePath);
try { fs.unlinkSync(tempPath); } catch { }
reject(err);
});
});
}
let persistCacheEnabled = true;
export function getCacheDir() {
return ensureCacheDir();
}
export function getCacheSize(): string {
const dir = ensureCacheDir();
if (!fs.existsSync(dir)) return '0 B';
let totalSize = 0;
try {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
try {
const stat = fs.statSync(filePath);
if (stat.isFile()) {
totalSize += stat.size;
}
} catch { }
}
} catch (e) {
console.error('[Proxy] Error calculating cache size:', e);
}
if (totalSize < 1024) return `${totalSize} B`;
if (totalSize < 1024 * 1024) return `${(totalSize / 1024).toFixed(1)} KB`;
if (totalSize < 1024 * 1024 * 1024) return `${(totalSize / (1024 * 1024)).toFixed(1)} MB`;
return `${(totalSize / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
export function isPersistCacheEnabled() {
return persistCacheEnabled;
}
export function setPersistCache(persist: boolean) {
persistCacheEnabled = persist;
console.log(`[Proxy] Cache persistence set to: ${persist}`);
}
export function clearCacheNow() {
const dir = ensureCacheDir();
if (fs.existsSync(dir)) {
console.log(`[Proxy] Clearing cache directory: ${dir}`);
// 终止所有下载任务
for (const [, task] of downloadTasks) {
if (task.abortController) {
task.abortController.abort();
}
}
downloadTasks.clear();
try {
fs.rmSync(dir, { recursive: true, force: true });
fs.mkdirSync(dir, { recursive: true });
console.log('[Proxy] Cache cleared');
} catch (e) {
console.error('[Proxy] Failed to clear cache:', e);
}
}
}
export function cleanupCache() {
if (!persistCacheEnabled && CACHE_DIR && fs.existsSync(CACHE_DIR)) {
console.log(`[Proxy] Cleaning up cache directory: ${CACHE_DIR}`);
// 终止所有下载任务
for (const [, task] of downloadTasks) {
if (task.abortController) {
task.abortController.abort();
}
}
downloadTasks.clear();
try {
fs.rmSync(CACHE_DIR, { recursive: true, force: true });
console.log('[Proxy] Cache cleanup complete');
} catch (e) {
console.error('[Proxy] Failed to cleanup cache:', e);
}
}
}
/**
* 清理过期的临时文件
*/
function cleanupTempFiles() {
const dir = ensureCacheDir();
try {
const files = fs.readdirSync(dir);
const now = Date.now();
for (const file of files) {
if (file.endsWith('.tmp')) {
const filePath = path.join(dir, file);
const cacheFilePath = filePath.replace('.tmp', '');
// 如果没有正在下载这个文件,且临时文件超过 1 小时,删除它
if (!downloadTasks.has(cacheFilePath)) {
try {
const stat = fs.statSync(filePath);
if (now - stat.mtimeMs > 3600 * 1000) {
fs.unlinkSync(filePath);
console.log(`[Proxy] Cleaned up stale temp file: ${file}`);
}
} catch { }
}
}
}
} catch (e) {
console.error('[Proxy] Error cleaning up temp files:', e);
}
}
export function startProxyServer(persistCache: boolean = true) {
persistCacheEnabled = persistCache;
console.log(`[Proxy] Persist cache: ${persistCache}`);
// 定期清理临时文件
setInterval(cleanupTempFiles, 30 * 60 * 1000);
const server = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Range');
if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}
if (req.method === 'HEAD') {
res.setHeader('Accept-Ranges', 'bytes');
res.statusCode = 200;
res.end();
return;
}
try {
const parsedUrl = new URL(req.url || '', `http://localhost:${PORT}`);
if (parsedUrl.pathname !== '/music') {
res.writeHead(404);
res.end('Not Found');
return;
}
const id = parsedUrl.searchParams.get('id');
const source = parsedUrl.searchParams.get('source');
const quality = parsedUrl.searchParams.get('quality') || 'standard';
if (!id || !source) {
res.writeHead(400);
res.end('Missing id or source');
return;
}
const cacheKey = `${source}:${id}:${quality}`;
const cacheFilePath = getCachePath(source, id, quality);
// 1. 检查完整缓存
if (isValidCacheFile(cacheFilePath)) {
console.log(`[Proxy] Serving from complete cache: ${cacheFilePath}`);
const success = serveFromCache(req, res, cacheFilePath);
if (success) return;
// 缓存无效,清理
console.warn('[Proxy] Cache file invalid, cleaning up...');
try {
fs.unlinkSync(cacheFilePath);
fs.unlinkSync(getMetadataPath(cacheFilePath));
} catch { }
}
// 2. 解析 URL
let playUrl: string | null = null;
const memCached = urlCache.get(cacheKey);
if (memCached && Date.now() < memCached.expiresAt) {
playUrl = memCached.url;
}
if (!playUrl) {
console.log(`[Proxy] Resolving URL for ${cacheKey}...`);
playUrl = await fetchFreshUrl(source, id, quality);
}
if (!playUrl) {
res.writeHead(500);
res.end('Failed to Obtain URL');
return;
}
// 3. 代理和缓存
const maxAttempts = 3;
let currentAttempt = 0;
let lastError: any = null;
while (currentAttempt < maxAttempts) {
try {
await proxyAndCache(req, res, playUrl, cacheFilePath, cacheKey);
break;
} catch (e: any) {
lastError = e;
currentAttempt++;
console.warn(`[Proxy] Proxy error (Attempt ${currentAttempt}/${maxAttempts}):`, e);
if (currentAttempt < maxAttempts) {
console.log('[Proxy] Error occurred, refreshing URL from plugin...');
urlCache.delete(cacheKey);
const newUrl = await fetchFreshUrl(source, id, quality);
if (newUrl) {
playUrl = newUrl;
continue;
} else {
console.error('[Proxy] Failed to refresh URL');
}
}
if (!res.headersSent) {
res.writeHead(lastError?.statusCode || 502);
res.end('Proxy Error');
}
break;
}
}
} catch (err) {
console.error('[Proxy] Internal Error:', err);
if (!res.headersSent) {
res.writeHead(500);
res.end('Internal Server Error');
}
}
});
server.listen(PORT, '127.0.0.1', () => {
ensureCacheDir();
cleanupTempFiles();
console.log(`[Proxy] Server running at http://127.0.0.1:${PORT}/music`);
console.log(`[Proxy] Cache dir: ${CACHE_DIR}`);
});
return server;
}

166
src/main/qzpController.ts Normal file
View File

@@ -0,0 +1,166 @@
//@ts-ignore
import { spawn, ChildProcess } from 'child_process';
import { Socket } from 'net';
import { EventEmitter } from 'events';
import path from 'path';
export class QzpController extends EventEmitter {
private process: ChildProcess | null = null;
private socket: Socket | null = null;
private ipcPath: string;
private messageBuffer: string = '';
constructor(ipcPath?: string) {
super();
this.ipcPath = ipcPath || this.getIpcPath();
}
private getIpcPath(): string {
if (process.platform === 'win32') {
return '\\\\.\\pipe\\qzplayer';
}
return '/tmp/qzmusic_mpv_socket';
}
private getCorePath(): string {
const appRoot = process.env.APP_ROOT || process.cwd();
if (process.platform === 'win32') {
return path.join(appRoot, 'core', 'qzplayer.exe');
}
return "qzplayer"
}
start() {
const playerPath = this.getCorePath();
console.log('Starting QZPlayer from:', playerPath);
this.process = spawn(playerPath);
this.process.on('error', (err) => {
console.error('Failed to start QZPlayer:', err);
this.emit('error', err);
});
this.process.on('exit', (code, signal) => {
console.log(`QZPlayer exited with code ${code} and signal ${signal}`);
this.emit('exit', { code, signal });
this.socket?.destroy();
});
this.tryConnect();
}
private tryConnect(retries = 10) {
if (retries <= 0) {
console.error('Could not connect to QZPlayer socket after multiple attempts.');
return;
}
setTimeout(() => {
this.socket = new Socket();
this.socket.on('connect', () => {
console.log('Connected to QZPlayer IPC socket');
this.emit('ready');
this.send(['observe_property', 1, 'pause']);
this.send(['observe_property', 2, 'time-pos']);
this.send(['observe_property', 3, 'duration']);
this.send(['observe_property', 4, 'idle-active']);
this.send(['observe_property', 5, 'eof-reached']);
this.send(['set_property', 'volume', 50])
});
this.socket.on('data', (data) => {
this.handleData(data);
});
this.socket.on('error', (_) => {
this.socket?.destroy();
this.tryConnect(retries - 1);
});
this.socket.connect(this.ipcPath);
}, 500);
}
private handleData(data: Buffer) {
// Determine message boundaries by newline
const raw = data.toString();
this.messageBuffer += raw;
const messages = this.messageBuffer.split('\n');
// The last part might be an incomplete message, save it back to buffer
this.messageBuffer = messages.pop() || '';
for (const msg of messages) {
if (!msg.trim()) continue;
//console.log('[IPC]', msg); // User requested raw communication
try {
const json = JSON.parse(msg);
this.emit('message', json);
// Handle specific events
if (json.event) {
this.emit('event', json);
}
} catch (e) {
console.error('Failed to parse QZPlayer message:', msg);
}
}
}
async send(command: any[]) {
if (!this.socket || this.socket.destroyed) {
console.warn('QZPlayer socket not connected');
return;
}
const payload = JSON.stringify({ command });
console.log('[QZPlayer TX]', payload); // User requested raw communication
this.socket.write(payload + '\n');
}
// Convenience methods
async load(url: string) {
return this.send(['loadfile', url]);
}
async play() {
return this.send(['set_property', 'pause', false]);
}
async pause() {
return this.send(['set_property', 'pause', true]);
}
async togglePause() {
return this.send(['cycle', 'pause']);
}
async stop() {
return this.send(['stop']);
}
async setVolume(vol: number) {
return this.send(['set_property', 'volume', vol]);
}
async seek(seconds: number) {
return this.send(['seek', seconds, 'absolute']);
}
destroy() {
if (this.process) {
console.log('Killing QZPlayer process...');
this.process.kill();
this.process = null;
}
if (this.socket) {
this.socket.destroy();
this.socket = null;
}
}
}

65
src/main/settingsStore.ts Normal file
View File

@@ -0,0 +1,65 @@
import fs from 'fs';
import path from 'path';
import { app } from 'electron';
export interface AppSettings {
// Cache
persistCache: boolean;
// Appearance
theme: 'dark' | 'light';
accentColor: string;
}
const DEFAULT_SETTINGS: AppSettings = {
persistCache: true,
theme: 'dark',
accentColor: '#ec4141', // Default red
};
let settingsCache: AppSettings | null = null;
function getSettingsPath(): string {
return path.join(app.getPath('userData'), 'settings.json');
}
export function loadSettings(): AppSettings {
if (settingsCache) return settingsCache;
const settingsPath = getSettingsPath();
try {
if (fs.existsSync(settingsPath)) {
const data = fs.readFileSync(settingsPath, 'utf-8');
settingsCache = { ...DEFAULT_SETTINGS, ...JSON.parse(data) };
console.log('[Settings] Loaded from disk:', settingsCache);
return settingsCache!;
}
} catch (e) {
console.error('[Settings] Failed to load settings:', e);
}
settingsCache = { ...DEFAULT_SETTINGS };
return settingsCache;
}
export function saveSettings(settings: Partial<AppSettings>): AppSettings {
settingsCache = { ...loadSettings(), ...settings };
const settingsPath = getSettingsPath();
try {
fs.writeFileSync(settingsPath, JSON.stringify(settingsCache, null, 2));
console.log('[Settings] Saved to disk:', settingsCache);
} catch (e) {
console.error('[Settings] Failed to save settings:', e);
}
return settingsCache;
}
export function getSetting<K extends keyof AppSettings>(key: K): AppSettings[K] {
return loadSettings()[key];
}
export function setSetting<K extends keyof AppSettings>(key: K, value: AppSettings[K]): void {
saveSettings({ [key]: value });
}

16
src/renderer/index.html Normal file
View File

@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="src/main.ts"></script>
</body>
</html>

View File

@@ -26,5 +26,5 @@ onMounted(async () => {
</script>
<style>
@import "./styles/main.css";
@import "styles/main.css";
</style>

View File

@@ -234,6 +234,7 @@ const drawSpectrum = () => {
// Adjust canvas size
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
@@ -241,7 +242,7 @@ const drawSpectrum = () => {
const width = rect.width;
const height = rect.height;
ctx.clearRect(0, 0, width, height);
const targetData = playerStore.spectrum;
@@ -251,8 +252,8 @@ const drawSpectrum = () => {
// Adjust speed (0.1 - 0.3) for desired smoothness
const lerpSpeed = 0.15;
for (let i = 0; i < 32; i++) {
const target = targetData[i] || 0;
currentData[i] = currentData[i] + (target - currentData[i]) * lerpSpeed;
const target = targetData[i] || 0;
currentData[i] = currentData[i] + (target - currentData[i]) * lerpSpeed;
}
// 2. Draw Smooth Wave
@@ -260,7 +261,7 @@ const drawSpectrum = () => {
ctx.moveTo(0, height);
const pointCount = currentData.length;
// Use a subset if desired, but 32 is fine.
// Use a subset if desired, but 32 is fine.
// We want the wave to be centered or span the width.
const step = width / (pointCount - 1);
@@ -272,14 +273,14 @@ const drawSpectrum = () => {
for (let i = 0; i < pointCount - 1; i++) {
const xCurr = i * step;
const yCurr = height - (currentData[i] * height * 0.5);
const xNext = (i + 1) * step;
const yNext = height - (currentData[i + 1] * height * 0.5);
// Control point for quadratic curve (midpoint)
const xMid = (xCurr + xNext) / 2;
const yMid = (yCurr + yNext) / 2;
ctx.quadraticCurveTo(xCurr, yCurr, xMid, yMid);
}
@@ -296,13 +297,13 @@ const drawSpectrum = () => {
const gradient = ctx.createLinearGradient(0, height - 200, 0, height);
gradient.addColorStop(0, 'rgba(255, 255, 255, 0.4)');
gradient.addColorStop(1, 'rgba(255, 255, 255, 0.05)');
ctx.fillStyle = gradient;
// Add blur effect
ctx.shadowBlur = 20;
ctx.shadowColor = 'rgba(255, 255, 255, 0.5)';
ctx.fill();
// Reset shadow for next frame (performance)

View File

@@ -179,7 +179,8 @@ const handleBarClick = (e: MouseEvent) => {
};
// Utils
const formatTime = (seconds: number) => {
const formatTime = (seconds2: number) => {
const seconds = Math.floor(seconds2 / 1000);
if (!seconds || isNaN(seconds)) return '00:00';
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);

View File

@@ -27,7 +27,6 @@ const hasSongs = computed(() => playerStore.playlist.length > 0);
</script>
<style>
/* 关键修复:全局重置盒模型 */
/* 这确保 width: 100% + padding 不会撑破容器 */
*, *::before, *::after {
box-sizing: border-box;
@@ -67,13 +66,12 @@ body {
flex-direction: column;
position: relative;
overflow: hidden;
/* 关键修复:防止 flex 子项内容过宽撑开容器 */
min-width: 0;
}
.page-content {
flex: 1;
overflow-y: auto; /* 只允许内容区域滚动 */
overflow-y: auto;
padding: 0;
background-color: var(--color-bg-primary);
position: relative;

View File

@@ -4,7 +4,6 @@ import { createPinia } from 'pinia'
import { createRouter, createWebHashHistory } from 'vue-router'
import App from './App.vue'
import TDesign from 'tdesign-vue-next'
import 'tdesign-vue-next/es/style/index.css'
const pinia = createPinia()
@@ -42,7 +41,6 @@ const router = createRouter({
const app = createApp(App)
app.use(pinia)
app.use(router)
app.use(TDesign)
app.mount('#app')
// --- TEST: Auto Play Specific Song ---

View File

@@ -1,7 +1,8 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ref, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import type { Song } from '../types/song';
import { parseLyric } from '../utils/lyricParser';
export enum PlayMode {
List = 'list',
@@ -24,9 +25,19 @@ export const usePlayerStore = defineStore('player', () => {
// State
const isPlaying = ref(false);
const currentSong = ref<Song | null>(null);
const volume = ref(50);
const duration = ref(0);
const currentTime = ref(0);
const savedVolume = localStorage.getItem('qz-player-volume');
const volume = ref(savedVolume ? Number(savedVolume) : 50); // 1~100
// Persistence & Sync
watch(volume, (newVol) => {
localStorage.setItem('qz-player-volume', newVol.toString());
});
// Sync initial volume to backend
if (window.electronAPI?.qzplayer) {
window.electronAPI.qzplayer.setVolume(volume.value).catch(console.error);
}
const duration = ref(0); //毫秒级
const currentTime = ref(0); //毫秒级
// Audio Visualization State
const loudness = ref(0);
@@ -45,8 +56,10 @@ export const usePlayerStore = defineStore('player', () => {
const MAX_RETRY_COUNT = 3;
const hasRetriedWithFreshUrl = ref(false);
// --- Helpers ---
// Lyrics State
const lyrics = ref<{ lines: any[] }>({ lines: [] });
// --- Helpers ---
const activateDummyAudio = async () => {
if (dummyAudio.paused) {
try {
@@ -77,8 +90,6 @@ export const usePlayerStore = defineStore('player', () => {
// --- Actions ---
const setPlaylist = async (list: any[], startIndex = 0) => {
playlist.value = list;
currentIndex.value = startIndex;
@@ -98,12 +109,13 @@ export const usePlayerStore = defineStore('player', () => {
await activateDummyAudio();
updateMediaSession(song);
fetchLyrics(song);
// 1. Get URL (Cache -> Network)
// Get URL (Cache -> Network)
let playUrl = song.url;
if (song.type === 'Remote' && song.source) {
// Use Local Proxy
const quality = 'jymaster';
const quality = 'hires';
playUrl = `http://localhost:5266/music?source=${song.source}&id=${song.id}&quality=${quality}`;
console.log('[Player] Using Proxy:', playUrl);
}
@@ -120,11 +132,33 @@ export const usePlayerStore = defineStore('player', () => {
} catch (e) {
// IPC call failed (rare), handle sync error
console.error("IPC Play request failed:", e);
handlePlayError();
handlePlayError().then();
}
} else {
console.warn("Song has no URL");
handlePlayError();
handlePlayError().then();
}
};
const fetchLyrics = async (song: Song) => {
lyrics.value = { lines: [] }; // Reset
if (!song || !song.id) return;
try {
// Check if plugin API exists
if (window.electronAPI?.plugin?.getLyric) {
const rawLyric = await window.electronAPI.plugin.getLyric(song.source || 'kw', song.id.toString());
if (rawLyric) {
const parsedLines = parseLyric(rawLyric);
if (parsedLines) {
lyrics.value = { lines: parsedLines };
}
console.log(lyrics)
}
} else {
MessagePlugin.warning("当前插件不支持歌词获取").then()
}
} catch (e) {
console.error('Failed to fetch lyrics:', e);
}
};
@@ -145,7 +179,7 @@ export const usePlayerStore = defineStore('player', () => {
navigator.mediaSession.setActionHandler('seekto', (details) => {
if (details.seekTime != null) {
seek(details.seekTime);
seek(details.seekTime).then();
}
});
};
@@ -182,7 +216,7 @@ export const usePlayerStore = defineStore('player', () => {
// Normal error handling
playErrorCount.value++;
hasRetriedWithFreshUrl.value = false; // Reset for next song
hasRetriedWithFreshUrl.value = false;
if (playlist.value.length === 0) {
isPlaying.value = false;
@@ -191,13 +225,13 @@ export const usePlayerStore = defineStore('player', () => {
return;
}
if (playErrorCount.value >= MAX_RETRY_COUNT) {
window.electronAPI.qzplayer.pause();
window.electronAPI.qzplayer.pause().then();
isPlaying.value = false;
MessagePlugin.error('连续多次播放失败,已停止播放');
MessagePlugin.error('连续多次播放失败,已停止播放').then();
playErrorCount.value = 0;
syncDummyAudioState(false);
} else {
MessagePlugin.warning(`播放失败,尝试播放下一首 (${playErrorCount.value}/${MAX_RETRY_COUNT})`);
MessagePlugin.warning(`播放失败,尝试播放下一首 (${playErrorCount.value}/${MAX_RETRY_COUNT})`).then();
setTimeout(() => next(false), 500);
}
};
@@ -209,11 +243,10 @@ export const usePlayerStore = defineStore('player', () => {
if (data.name === 'pause') {
const isPaused = data.data;
isPlaying.value = !isPaused;
// 核心qzplayer 暂停 -> 同步暂停 Dummy -> 浏览器更新 SMTC 状态
syncDummyAudioState(!isPaused);
}
if (data.name === 'time-pos') currentTime.value = data.data;
if (data.name === 'duration') duration.value = data.data;
if (data.name === 'time-pos') currentTime.value = data.data; //毫秒级
if (data.name === 'duration') duration.value = data.data; //毫秒级
if (data.name === 'loudness') loudness.value = data.data;
if (data.name === 'spectrum') spectrum.value = data.data;
}
@@ -223,7 +256,7 @@ export const usePlayerStore = defineStore('player', () => {
if (reason === 'eof') {
next(false);
} else if (reason === 'error') {
handlePlayError();
handlePlayError().then();
}
}
});
@@ -271,6 +304,8 @@ export const usePlayerStore = defineStore('player', () => {
setVolume,
seek,
toggleMode,
toggleFullScreen
toggleFullScreen,
lyrics,
fetchLyrics
};
});

View File

@@ -3,7 +3,6 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {

View File

@@ -16,6 +16,7 @@ export interface IElectronAPI {
plugin: {
call: (pluginId: string, method: string, args: any[]) => Promise<any>;
search: (pluginId: string, query: string, page: number, limit: number) => Promise<any>;
getLyric: (pluginId: string, id: string) => Promise<any>;
};
// Cache Control
getCacheInfo: () => Promise<{ path: string; size: string; persistCache: boolean }>;

View File

@@ -2,10 +2,27 @@
<div class="view-container search-view">
<div class="content-wrapper">
<div class="search-header">
<h1 class="search-title">搜索: "{{ query }}"</h1>
<span class="result-count">找到 {{ total }} 个结果</span>
<div class="header-left">
<h1 class="search-title">搜索: "{{ query }}"</h1>
<span class="result-count">找到 {{ total }} 个结果</span>
</div>
<button class="icon-btn" @click="showSettings = !showSettings" :class="{ active: showSettings }" title="搜索设置">
<Icon icon="lucide:settings-2" />
</button>
</div>
<transition name="slide-fade">
<div class="settings-panel" v-if="showSettings">
<div class="setting-item">
<span class="setting-label">每页显示: {{ limit }} </span>
<div class="slider-container">
<input type="range" min="10" max="100" step="10" v-model.number="limit" class="setting-slider">
<div class="slider-track" :style="{ width: ((limit - 10) / 90) * 100 + '%' }"></div>
</div>
</div>
</div>
</transition>
<div class="song-list-container" v-if="!loading && songs.length > 0">
<div class="list-header">
<div class="col-index">#</div>
@@ -71,19 +88,21 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
import { Icon } from '@iconify/vue';
import { usePlayerStore } from '../stores/player';
import { transformSearchSong } from '../utils/songUtils';
import type { Song } from '../types/song';
const route = useRoute();
const router = useRouter();
const playerStore = usePlayerStore();
const query = computed(() => route.query.q as string || '');
const currentPage = ref(1);
const limit = ref(30);
const showSettings = ref(false);
const savedLimit = localStorage.getItem('qz-search-limit');
const limit = ref(savedLimit ? Number(savedLimit) : 30);
const total = ref(0);
const loading = ref(false);
const songs = ref<Song[]>([]);
@@ -110,7 +129,7 @@ const visiblePages = computed(() => {
start = Math.max(1, start - ((current + delta) - total));
}
const pages = [];
const pages: number[] = [];
for (let i = start; i <= end; i++) {
pages.push(i);
}
@@ -191,6 +210,12 @@ watch(query, () => {
currentPage.value = 1;
fetchData();
}, { immediate: true });
watch(limit, (newLimit) => {
localStorage.setItem('qz-search-limit', newLimit.toString());
currentPage.value = 1;
fetchData();
});
</script>
@@ -210,6 +235,12 @@ watch(query, () => {
.search-header {
margin-bottom: 24px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header-left {
text-align: left;
}
@@ -239,6 +270,113 @@ watch(query, () => {
color: var(--color-text-muted);
}
.icon-btn {
background: transparent;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
width: 36px;
height: 36px;
transition: all 0.2s;
}
.icon-btn:hover {
background: var(--color-bg-tertiary);
color: var(--color-text-primary);
}
.icon-btn.active {
background: var(--color-bg-tertiary);
color: var(--color-accent);
}
/* Settings Panel */
.settings-panel {
background: var(--color-bg-secondary);
border-radius: var(--radius-lg);
padding: 16px 20px;
margin-bottom: 20px;
border: 1px solid var(--color-border);
}
.setting-item {
display: flex;
align-items: center;
gap: 16px;
}
.setting-label {
font-size: 14px;
color: var(--color-text-secondary);
min-width: 100px;
}
.slider-container {
position: relative;
width: 200px;
height: 4px;
background: var(--color-bg-tertiary);
border-radius: 2px;
display: flex;
align-items: center;
}
.setting-slider {
appearance: none;
position: absolute;
width: 100%;
height: 100%;
background: transparent;
top: 0;
left: 0;
margin: 0;
z-index: 2;
cursor: pointer;
}
.setting-slider::-webkit-slider-thumb {
-webkit-appearance: none;
width: 12px;
height: 12px;
border-radius: 50%;
background: var(--color-accent);
cursor: pointer;
box-shadow: 0 0 4px rgba(0,0,0,0.2);
}
.slider-track {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: var(--color-accent);
border-radius: 2px;
pointer-events: none;
z-index: 1;
}
.slide-fade-enter-active,
.slide-fade-leave-active {
transition: all 0.3s ease;
max-height: 100px;
overflow: hidden;
opacity: 1;
}
.slide-fade-enter-from,
.slide-fade-leave-to {
max-height: 0;
opacity: 0;
margin-bottom: 0;
padding-top: 0;
padding-bottom: 0;
border-width: 0;
}
/* List Grid Layout */
.list-header, .song-item {
display: grid;