feat: Implement features and continuously optimize the proxy service

- Settings page UI
- Persist settings data
- Proxy server fixes & optimizations:
  - Fixed download latency caused by Range Seek
  - Improved cache stability
  - Implemented a dual-threading model to ensure smooth playback
- Optimized styles for the homepage TopBar and SideBar
- Added theme switching functionality
- Added theme color customization feature
This commit is contained in:
lqtmcstudio
2026-02-04 14:14:40 +08:00
parent c472ec06e5
commit 8eab16cbf5
13 changed files with 1935 additions and 323 deletions

View File

@@ -150,7 +150,7 @@ class MpvController extends EventEmitter {
} }
} }
} }
const require$1 = createRequire(import.meta.url); const require$2 = createRequire(import.meta.url);
class PluginSystem { class PluginSystem {
constructor(pluginId) { constructor(pluginId) {
__publicField(this, "pluginId"); __publicField(this, "pluginId");
@@ -169,8 +169,8 @@ class PluginSystem {
if (!fs.existsSync(pluginPath)) { if (!fs.existsSync(pluginPath)) {
throw new Error(`Plugin ${this.pluginId} not found`); throw new Error(`Plugin ${this.pluginId} not found`);
} }
delete require$1.cache[require$1.resolve(pluginPath)]; delete require$2.cache[require$2.resolve(pluginPath)];
this.plugin = require$1(pluginPath); this.plugin = require$2(pluginPath);
} catch (e) { } catch (e) {
console.error(`[PluginSystem] load failed:`, e); console.error(`[PluginSystem] load failed:`, e);
this.plugin = null; this.plugin = null;
@@ -211,7 +211,7 @@ function ensureCacheDir() {
return CACHE_DIR; return CACHE_DIR;
} }
const urlCache = /* @__PURE__ */ new Map(); const urlCache = /* @__PURE__ */ new Map();
const downloadingFiles = /* @__PURE__ */ new Map(); const downloadTasks = /* @__PURE__ */ new Map();
function getCachePath(source, id, quality) { function getCachePath(source, id, quality) {
const dir = ensureCacheDir(); const dir = ensureCacheDir();
const safeId = id.replace(/[^a-z0-9]/gi, "_"); const safeId = id.replace(/[^a-z0-9]/gi, "_");
@@ -220,6 +220,9 @@ function getCachePath(source, id, quality) {
function getMetadataPath(cachePath) { function getMetadataPath(cachePath) {
return cachePath + ".meta"; return cachePath + ".meta";
} }
function getTempPath(cachePath) {
return cachePath + ".tmp";
}
function readMetadata(cachePath) { function readMetadata(cachePath) {
const metaPath = getMetadataPath(cachePath); const metaPath = getMetadataPath(cachePath);
try { try {
@@ -258,11 +261,15 @@ async function fetchFreshUrl(source, id, quality) {
} }
} }
function isValidCacheFile(filePath) { function isValidCacheFile(filePath) {
try {
const metadata = readMetadata(filePath); const metadata = readMetadata(filePath);
if (!metadata || !metadata.complete) return false; if (!metadata || !metadata.complete) return false;
if (!fs.existsSync(filePath)) return false; if (!fs.existsSync(filePath)) return false;
const stat = fs.statSync(filePath); const stat = fs.statSync(filePath);
return stat.size === metadata.totalSize && stat.size > 1024; return stat.size === metadata.totalSize && stat.size > 1024;
} catch {
return false;
}
} }
function parseRangeHeader(range, fileSize) { function parseRangeHeader(range, fileSize) {
if (!range) return null; if (!range) return null;
@@ -275,6 +282,7 @@ function parseRangeHeader(range, fileSize) {
return { start, end }; return { start, end };
} }
function serveFromCache(req, res, filePath) { function serveFromCache(req, res, filePath) {
try {
const metadata = readMetadata(filePath); const metadata = readMetadata(filePath);
if (!metadata) { if (!metadata) {
console.warn("[Proxy] No metadata for cache file"); console.warn("[Proxy] No metadata for cache file");
@@ -314,68 +322,230 @@ function serveFromCache(req, res, filePath) {
}); });
} }
return true; return true;
} catch (e) {
console.error("[Proxy] Error serving from cache:", e);
return false;
}
} }
async function proxyWithoutCache(req, res, targetUrl) { async function proxyRangeDirect(req, res, targetUrl, totalSize, contentType) {
const headers = {}; const headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
};
if (req.headers.range) { if (req.headers.range) {
headers["Range"] = req.headers.range; headers["Range"] = req.headers.range;
} }
headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
const response = await fetch(targetUrl, { const response = await fetch(targetUrl, {
method: "GET", method: "GET",
headers headers
}); });
if (!response.ok) { if (!response.ok && response.status !== 206) {
throw { statusCode: response.status, statusText: response.statusText }; throw { statusCode: response.status, statusText: response.statusText };
} }
const headersToForward = ["content-type", "content-length", "content-range", "accept-ranges"]; const responseContentType = response.headers.get("content-type") || contentType || "audio/mpeg";
headersToForward.forEach((h) => { const contentLength = response.headers.get("content-length");
const val = response.headers.get(h); const contentRange = response.headers.get("content-range");
if (val) res.setHeader(h, val); if (response.status === 206 && contentRange) {
res.writeHead(206, {
"Content-Type": responseContentType,
"Content-Length": contentLength || "",
"Content-Range": contentRange,
"Accept-Ranges": "bytes"
}); });
res.statusCode = response.status; } else {
res.writeHead(200, {
"Content-Type": responseContentType,
"Content-Length": contentLength || "",
"Accept-Ranges": "bytes"
});
}
if (!response.body) { if (!response.body) {
res.end(); res.end();
return; return;
} }
const nodeStream = Readable.fromWeb(response.body); const nodeStream = Readable.fromWeb(response.body);
nodeStream.pipe(res); nodeStream.pipe(res);
nodeStream.on("error", (err) => { return new Promise((resolve, reject) => {
console.error("[Proxy] Stream error:", err); nodeStream.on("end", resolve);
if (!res.headersSent) { nodeStream.on("error", reject);
res.writeHead(502); res.on("close", () => {
res.end("Proxy stream error"); nodeStream.destroy();
} resolve();
});
}); });
} }
async function proxyAndCache(req, res, targetUrl, cacheFilePath) { function serveFromPartialCache(req, res, filePath, task) {
const requestedRange = req.headers.range; try {
const downloadState = downloadingFiles.get(cacheFilePath); const tempPath = getTempPath(filePath);
if (downloadState) { if (!fs.existsSync(tempPath)) return false;
console.log(`[Proxy] File already downloading, current: ${downloadState.currentSize}/${downloadState.totalSize}`); const range = parseRangeHeader(req.headers.range, task.totalSize);
if (requestedRange) { if (!range) return false;
const range = parseRangeHeader(requestedRange, downloadState.totalSize);
if (range && range.end < downloadState.currentSize) {
console.log(`[Proxy] Serving range from in-progress cache`);
const { start, end } = range; const { start, end } = range;
if (end >= task.currentSize) {
return false;
}
const chunksize = end - start + 1; const chunksize = end - start + 1;
res.writeHead(206, { res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/${downloadState.totalSize}`, "Content-Range": `bytes ${start}-${end}/${task.totalSize}`,
"Accept-Ranges": "bytes", "Accept-Ranges": "bytes",
"Content-Length": chunksize, "Content-Length": chunksize,
"Content-Type": "audio/mpeg" "Content-Type": task.contentType || "audio/mpeg"
}); });
const file = fs.createReadStream(cacheFilePath, { start, end }); const file = fs.createReadStream(tempPath, { start, end });
file.pipe(res); file.pipe(res);
return true;
} catch (e) {
console.error("[Proxy] Error serving from partial cache:", e);
return false;
}
}
function startBackgroundDownload(targetUrl, cacheFilePath, cacheKey) {
const existingTask = downloadTasks.get(cacheFilePath);
if (existingTask) {
return existingTask;
}
const abortController = new AbortController();
const task = {
currentSize: 0,
totalSize: 0,
contentType: "audio/mpeg",
abortController,
promise: null
};
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;
}
const nodeStream = Readable.fromWeb(response.body);
await new Promise((resolve, reject) => {
nodeStream.on("data", (chunk) => {
task.currentSize += chunk.length;
});
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,
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) => {
console.error("[Proxy] Background download stream error:", err);
fileStream.destroy();
try {
fs.unlinkSync(tempPath);
} catch {
}
reject(err);
});
});
} catch (e) {
if (e.name !== "AbortError") {
console.error("[Proxy] Background download failed:", e);
}
try {
fs.unlinkSync(tempPath);
} catch {
}
} finally {
downloadTasks.delete(cacheFilePath);
}
})();
return task;
}
async function proxyAndCache(req, res, targetUrl, cacheFilePath, cacheKey) {
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 safeEnd = Math.floor(task.currentSize * 0.95);
if (range.end < safeEnd && range.start < safeEnd) {
console.log(`[Proxy] Serving range ${range.start}-${range.end} from partial cache (downloaded: ${task.currentSize})`);
if (serveFromPartialCache(req, res, cacheFilePath, task)) {
return; return;
} }
} }
await proxyWithoutCache(req, res, targetUrl); console.log(`[Proxy] Range ${range.start}-${range.end} not cached yet (downloaded: ${task.currentSize}), proxying directly`);
await proxyRangeDirect(req, res, targetUrl, task.totalSize, task.contentType);
return; return;
} }
if (requestedRange && !requestedRange.startsWith("bytes=0-")) { }
console.log(`[Proxy] Range request without cache: ${requestedRange}`); await proxyRangeDirect(req, res, targetUrl, task.totalSize, task.contentType);
await proxyWithoutCache(req, res, targetUrl); return;
}
if (isSeekRequest) {
console.log(`[Proxy] Seek request: ${requestedRange}, starting background download`);
startBackgroundDownload(targetUrl, cacheFilePath);
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 contentType2 = headResponse.headers.get("content-type") || "audio/mpeg";
await proxyRangeDirect(req, res, targetUrl, totalSize, contentType2);
return; return;
} }
const headers = { const headers = {
@@ -392,8 +562,10 @@ async function proxyAndCache(req, res, targetUrl, cacheFilePath) {
const contentType = response.headers.get("content-type") || "audio/mpeg"; const contentType = response.headers.get("content-type") || "audio/mpeg";
if (!contentLength) { if (!contentLength) {
console.warn("[Proxy] No content-length, proxying without cache"); console.warn("[Proxy] No content-length, proxying without cache");
res.setHeader("Content-Type", contentType); res.writeHead(200, {
res.statusCode = 200; "Content-Type": contentType,
"Accept-Ranges": "bytes"
});
if (response.body) { if (response.body) {
const nodeStream2 = Readable.fromWeb(response.body); const nodeStream2 = Readable.fromWeb(response.body);
nodeStream2.pipe(res); nodeStream2.pipe(res);
@@ -402,20 +574,22 @@ async function proxyAndCache(req, res, targetUrl, cacheFilePath) {
} }
return; return;
} }
const tempPath = cacheFilePath + ".tmp"; const tempPath = getTempPath(cacheFilePath);
try { try {
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
if (fs.existsSync(cacheFilePath)) fs.unlinkSync(cacheFilePath); if (fs.existsSync(cacheFilePath)) fs.unlinkSync(cacheFilePath);
} catch (e) { } catch {
console.error("[Proxy] Cleanup error:", e);
} }
const fileStream = fs.createWriteStream(tempPath); const fileStream = fs.createWriteStream(tempPath);
downloadingFiles.set(cacheFilePath, { task = {
currentSize: 0, currentSize: 0,
totalSize: contentLength, totalSize: contentLength,
writeStream: fileStream contentType,
}); abortController: null,
console.log(`[Proxy] Starting download: ${cacheFilePath} (${contentLength} bytes)`); promise: null
};
downloadTasks.set(cacheFilePath, task);
console.log(`[Proxy] Starting stream download: ${cacheFilePath} (${contentLength} bytes)`);
res.writeHead(200, { res.writeHead(200, {
"Content-Length": contentLength, "Content-Length": contentLength,
"Content-Type": contentType, "Content-Type": contentType,
@@ -423,24 +597,21 @@ async function proxyAndCache(req, res, targetUrl, cacheFilePath) {
}); });
if (!response.body) { if (!response.body) {
res.end(); res.end();
downloadingFiles.delete(cacheFilePath); downloadTasks.delete(cacheFilePath);
return; return;
} }
const nodeStream = Readable.fromWeb(response.body); const nodeStream = Readable.fromWeb(response.body);
const passThrough = new PassThrough(); const passThrough = new PassThrough();
let downloadedBytes = 0;
passThrough.on("data", (chunk) => { passThrough.on("data", (chunk) => {
downloadedBytes += chunk.length; if (task) {
const state = downloadingFiles.get(cacheFilePath); task.currentSize += chunk.length;
if (state) {
state.currentSize = downloadedBytes;
} }
}); });
passThrough.pipe(res); passThrough.pipe(res);
nodeStream.pipe(passThrough); nodeStream.pipe(passThrough);
nodeStream.pipe(fileStream); nodeStream.pipe(fileStream);
const cleanup = (success, error) => { const cleanup = (success, error) => {
downloadingFiles.delete(cacheFilePath); downloadTasks.delete(cacheFilePath);
if (success && fs.existsSync(tempPath)) { if (success && fs.existsSync(tempPath)) {
try { try {
const stat = fs.statSync(tempPath); const stat = fs.statSync(tempPath);
@@ -469,25 +640,83 @@ async function proxyAndCache(req, res, targetUrl, cacheFilePath) {
} }
} else if (!success) { } else if (!success) {
console.error("[Proxy] Download failed:", error); console.error("[Proxy] Download failed:", error);
try {
fs.unlinkSync(tempPath);
} catch {
}
} }
}; };
fileStream.on("finish", () => cleanup(true)); fileStream.on("finish", () => cleanup(true));
fileStream.on("error", (err) => cleanup(false, err)); fileStream.on("error", (err) => cleanup(false, err));
nodeStream.on("error", (err) => cleanup(false, err)); nodeStream.on("error", (err) => {
cleanup(false, err);
if (!res.headersSent) {
res.writeHead(502);
res.end("Proxy stream error");
}
});
res.on("close", () => { res.on("close", () => {
if (!res.writableEnded) { if (!res.writableEnded) {
console.log("[Proxy] Client disconnected during download"); console.log("[Proxy] Client disconnected, download continues in background");
} }
}); });
} }
let persistCacheEnabled = true; let persistCacheEnabled = true;
function getCacheDir() {
return ensureCacheDir();
}
function getCacheSize() {
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`;
}
function setPersistCache(persist) {
persistCacheEnabled = persist;
console.log(`[Proxy] Cache persistence set to: ${persist}`);
}
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);
}
}
}
function cleanupCache() { function cleanupCache() {
if (!persistCacheEnabled && CACHE_DIR && fs.existsSync(CACHE_DIR)) { if (!persistCacheEnabled && CACHE_DIR && fs.existsSync(CACHE_DIR)) {
console.log(`[Proxy] Cleaning up cache directory: ${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 { try {
fs.rmSync(CACHE_DIR, { recursive: true, force: true }); fs.rmSync(CACHE_DIR, { recursive: true, force: true });
console.log("[Proxy] Cache cleanup complete"); console.log("[Proxy] Cache cleanup complete");
@@ -496,9 +725,35 @@ function cleanupCache() {
} }
} }
} }
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", "");
if (!downloadTasks.has(cacheFilePath)) {
try {
const stat = fs.statSync(filePath);
if (now - stat.mtimeMs > 3600 * 1e3) {
fs.unlinkSync(filePath);
console.log(`[Proxy] Cleaned up stale temp file: ${file}`);
}
} catch {
}
}
}
}
} catch (e) {
console.error("[Proxy] Error cleaning up temp files:", e);
}
}
function startProxyServer(persistCache = true) { function startProxyServer(persistCache = true) {
persistCacheEnabled = persistCache; persistCacheEnabled = persistCache;
console.log(`[Proxy] Persist cache: ${persistCache}`); console.log(`[Proxy] Persist cache: ${persistCache}`);
setInterval(cleanupTempFiles, 30 * 60 * 1e3);
const server = http.createServer(async (req, res) => { const server = http.createServer(async (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS"); res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
@@ -556,14 +811,34 @@ function startProxyServer(persistCache = true) {
res.end("Failed to Obtain URL"); res.end("Failed to Obtain URL");
return; return;
} }
const maxAttempts = 3;
let currentAttempt = 0;
let lastError = null;
while (currentAttempt < maxAttempts) {
try { try {
await proxyAndCache(req, res, playUrl, cacheFilePath); await proxyAndCache(req, res, playUrl, cacheFilePath, cacheKey);
break;
} catch (e) { } catch (e) {
console.warn(`[Proxy] Proxy error:`, e); 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) { if (!res.headersSent) {
res.writeHead(e.statusCode || 502); res.writeHead((lastError == null ? void 0 : lastError.statusCode) || 502);
res.end("Proxy Error"); res.end("Proxy Error");
} }
break;
}
} }
} catch (err) { } catch (err) {
console.error("[Proxy] Internal Error:", err); console.error("[Proxy] Internal Error:", err);
@@ -575,12 +850,53 @@ function startProxyServer(persistCache = true) {
}); });
server.listen(PORT, "127.0.0.1", () => { server.listen(PORT, "127.0.0.1", () => {
ensureCacheDir(); ensureCacheDir();
cleanupTempFiles();
console.log(`[Proxy] Server running at http://127.0.0.1:${PORT}/music`); console.log(`[Proxy] Server running at http://127.0.0.1:${PORT}/music`);
console.log(`[Proxy] Cache dir: ${CACHE_DIR}`); console.log(`[Proxy] Cache dir: ${CACHE_DIR}`);
}); });
return server; return server;
} }
createRequire(import.meta.url); const DEFAULT_SETTINGS = {
persistCache: true,
theme: "dark",
accentColor: "#ec4141"
// Default red
};
let settingsCache = null;
function getSettingsPath() {
return path.join(app.getPath("userData"), "settings.json");
}
function loadSettings() {
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;
}
function saveSettings(settings) {
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;
}
function getSetting(key) {
return loadSettings()[key];
}
const require$1 = createRequire(import.meta.url);
const __dirname$1 = path$1.dirname(fileURLToPath(import.meta.url)); const __dirname$1 = path$1.dirname(fileURLToPath(import.meta.url));
process.env.APP_ROOT = path$1.join(__dirname$1, ".."); process.env.APP_ROOT = path$1.join(__dirname$1, "..");
const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"]; const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
@@ -646,6 +962,43 @@ ipcMain.handle(
return await plugin[method](...args); return await plugin[method](...args);
} }
); );
ipcMain.handle("cache:getInfo", () => {
const settings = loadSettings();
return {
path: getCacheDir(),
size: getCacheSize(),
persistCache: settings.persistCache
};
});
ipcMain.handle("cache:setPersist", (_, persist) => {
setPersistCache(persist);
saveSettings({ persistCache: persist });
});
ipcMain.handle("cache:openFolder", () => {
const dir = getCacheDir();
require$1("electron").shell.openPath(dir);
});
ipcMain.handle("cache:clear", () => {
clearCacheNow();
});
ipcMain.handle("settings:getAll", () => {
return loadSettings();
});
ipcMain.handle("settings:set", (_, settings) => {
return saveSettings(settings);
});
ipcMain.handle("settings:getTheme", () => {
return getSetting("theme");
});
ipcMain.handle("settings:setTheme", (_, theme) => {
saveSettings({ theme });
});
ipcMain.handle("settings:getAccentColor", () => {
return getSetting("accentColor");
});
ipcMain.handle("settings:setAccentColor", (_, color) => {
saveSettings({ accentColor: color });
});
app.on("window-all-closed", () => { app.on("window-all-closed", () => {
if (process.platform !== "darwin") { if (process.platform !== "darwin") {
app.quit(); app.quit();

View File

@@ -20,5 +20,19 @@ electron.contextBridge.exposeInMainWorld("electronAPI", {
// Plugin System // Plugin System
plugin: { plugin: {
call: (pluginId, method, args) => electron.ipcRenderer.invoke("plugin:call", pluginId, method, args) call: (pluginId, method, args) => electron.ipcRenderer.invoke("plugin:call", pluginId, method, args)
},
// Cache Control
getCacheInfo: () => electron.ipcRenderer.invoke("cache:getInfo"),
setCachePersist: (persist) => electron.ipcRenderer.invoke("cache:setPersist", persist),
openCacheFolder: () => electron.ipcRenderer.invoke("cache:openFolder"),
clearCache: () => electron.ipcRenderer.invoke("cache:clear"),
// Settings
settings: {
getAll: () => electron.ipcRenderer.invoke("settings:getAll"),
set: (settings) => electron.ipcRenderer.invoke("settings:set", settings),
getTheme: () => electron.ipcRenderer.invoke("settings:getTheme"),
setTheme: (theme) => electron.ipcRenderer.invoke("settings:setTheme", theme),
getAccentColor: () => electron.ipcRenderer.invoke("settings:getAccentColor"),
setAccentColor: (color) => electron.ipcRenderer.invoke("settings:setAccentColor", color)
} }
}); });

View File

@@ -4,8 +4,9 @@ import { fileURLToPath } from 'node:url'
import path from 'node:path' import path from 'node:path'
import fs from 'node:fs' import fs from 'node:fs'
import { MpvController } from './mpvController' import { MpvController } from './mpvController'
import { startProxyServer, cleanupCache } from './proxyServer' import { startProxyServer, cleanupCache, getCacheDir, getCacheSize, setPersistCache, clearCacheNow } from './proxyServer'
import { PluginSystem } from '../src/main/pluginSystem.ts' import { PluginSystem } from '../src/main/pluginSystem.ts'
import { loadSettings, saveSettings, getSetting, AppSettings } from './settingsStore'
// @ts-ignore // @ts-ignore
const require = createRequire(import.meta.url) const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url)) const __dirname = path.dirname(fileURLToPath(import.meta.url))
@@ -91,6 +92,55 @@ ipcMain.handle(
} }
) )
// Cache IPC Handlers
ipcMain.handle('cache:getInfo', () => {
const settings = loadSettings();
return {
path: getCacheDir(),
size: getCacheSize(),
persistCache: settings.persistCache
}
})
ipcMain.handle('cache:setPersist', (_, persist: boolean) => {
setPersistCache(persist)
saveSettings({ persistCache: persist })
})
ipcMain.handle('cache:openFolder', () => {
const dir = getCacheDir()
require('electron').shell.openPath(dir)
})
ipcMain.handle('cache:clear', () => {
clearCacheNow()
})
// Settings IPC Handlers
ipcMain.handle('settings:getAll', () => {
return loadSettings()
})
ipcMain.handle('settings:set', (_, settings: Partial<AppSettings>) => {
return saveSettings(settings)
})
ipcMain.handle('settings:getTheme', () => {
return getSetting('theme')
})
ipcMain.handle('settings:setTheme', (_, theme: 'dark' | 'light') => {
saveSettings({ theme })
})
ipcMain.handle('settings:getAccentColor', () => {
return getSetting('accentColor')
})
ipcMain.handle('settings:setAccentColor', (_, color: string) => {
saveSettings({ accentColor: color })
})
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
app.quit() app.quit()

View File

@@ -22,5 +22,21 @@ contextBridge.exposeInMainWorld('electronAPI', {
// Plugin System // Plugin System
plugin: { plugin: {
call: (pluginId: string, method: string, args: any[]) => ipcRenderer.invoke('plugin:call', pluginId, method, args) call: (pluginId: string, method: string, args: any[]) => ipcRenderer.invoke('plugin:call', pluginId, method, args)
},
// Cache Control
getCacheInfo: () => ipcRenderer.invoke('cache:getInfo'),
setCachePersist: (persist: boolean) => ipcRenderer.invoke('cache:setPersist', persist),
openCacheFolder: () => ipcRenderer.invoke('cache:openFolder'),
clearCache: () => ipcRenderer.invoke('cache:clear'),
// Settings
settings: {
getAll: () => ipcRenderer.invoke('settings:getAll'),
set: (settings: any) => ipcRenderer.invoke('settings:set', settings),
getTheme: () => ipcRenderer.invoke('settings:getTheme'),
setTheme: (theme: 'dark' | 'light') => ipcRenderer.invoke('settings:setTheme', theme),
getAccentColor: () => ipcRenderer.invoke('settings:getAccentColor'),
setAccentColor: (color: string) => ipcRenderer.invoke('settings:setAccentColor', color)
} }
}) })

View File

@@ -36,14 +36,19 @@ interface CacheMetadata {
createdAt: number; createdAt: number;
} }
// Memory cache for resolved URLs interface DownloadTask {
const urlCache = new Map<string, CacheEntry>();
// Track in-progress downloads with their current size
const downloadingFiles = new Map<string, {
currentSize: number; currentSize: number;
totalSize: number; totalSize: number;
writeStream: fs.WriteStream | null; contentType: string;
}>(); abortController: AbortController | null;
promise: Promise<void> | null;
}
// 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) { function getCachePath(source: string, id: string, quality: string) {
const dir = ensureCacheDir(); const dir = ensureCacheDir();
@@ -55,6 +60,10 @@ function getMetadataPath(cachePath: string): string {
return cachePath + '.meta'; return cachePath + '.meta';
} }
function getTempPath(cachePath: string): string {
return cachePath + '.tmp';
}
function readMetadata(cachePath: string): CacheMetadata | null { function readMetadata(cachePath: string): CacheMetadata | null {
const metaPath = getMetadataPath(cachePath); const metaPath = getMetadataPath(cachePath);
try { try {
@@ -96,14 +105,16 @@ async function fetchFreshUrl(source: string, id: string, quality: string): Promi
} }
function isValidCacheFile(filePath: string): boolean { function isValidCacheFile(filePath: string): boolean {
try {
const metadata = readMetadata(filePath); const metadata = readMetadata(filePath);
if (!metadata || !metadata.complete) return false; if (!metadata || !metadata.complete) return false;
if (!fs.existsSync(filePath)) return false; if (!fs.existsSync(filePath)) return false;
const stat = fs.statSync(filePath);
// Verify the file size matches expected total const stat = fs.statSync(filePath);
return stat.size === metadata.totalSize && stat.size > 1024; return stat.size === metadata.totalSize && stat.size > 1024;
} catch {
return false;
}
} }
function parseRangeHeader(range: string | undefined, fileSize: number): { start: number; end: number } | null { function parseRangeHeader(range: string | undefined, fileSize: number): { start: number; end: number } | null {
@@ -122,6 +133,7 @@ function parseRangeHeader(range: string | undefined, fileSize: number): { start:
} }
function serveFromCache(req: http.IncomingMessage, res: http.ServerResponse, filePath: string): boolean { function serveFromCache(req: http.IncomingMessage, res: http.ServerResponse, filePath: string): boolean {
try {
const metadata = readMetadata(filePath); const metadata = readMetadata(filePath);
if (!metadata) { if (!metadata) {
console.warn('[Proxy] No metadata for cache file'); console.warn('[Proxy] No metadata for cache file');
@@ -167,36 +179,58 @@ function serveFromCache(req: http.IncomingMessage, res: http.ServerResponse, fil
}); });
} }
return true; return true;
} catch (e) {
console.error('[Proxy] Error serving from cache:', e);
return false;
}
} }
async function proxyWithoutCache( /**
* 直接代理 Range 请求,不缓存(用于 seek 到未下载的位置)
*/
async function proxyRangeDirect(
req: http.IncomingMessage, req: http.IncomingMessage,
res: http.ServerResponse, res: http.ServerResponse,
targetUrl: string targetUrl: string,
totalSize: number,
contentType: string
): Promise<void> { ): Promise<void> {
const headers: Record<string, string> = {}; const headers: Record<string, string> = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
};
if (req.headers.range) { if (req.headers.range) {
headers['Range'] = req.headers.range; headers['Range'] = req.headers.range;
} }
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
const response = await fetch(targetUrl, { const response = await fetch(targetUrl, {
method: 'GET', method: 'GET',
headers: headers, headers: headers,
}); });
if (!response.ok) { if (!response.ok && response.status !== 206) {
throw { statusCode: response.status, statusText: response.statusText }; throw { statusCode: response.status, statusText: response.statusText };
} }
const headersToForward = ['content-type', 'content-length', 'content-range', 'accept-ranges']; // Forward response headers
headersToForward.forEach(h => { const responseContentType = response.headers.get('content-type') || contentType || 'audio/mpeg';
const val = response.headers.get(h); const contentLength = response.headers.get('content-length');
if (val) res.setHeader(h, val); const contentRange = response.headers.get('content-range');
});
res.statusCode = response.status; 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) { if (!response.body) {
res.end(); res.end();
@@ -207,67 +241,259 @@ async function proxyWithoutCache(
const nodeStream = Readable.fromWeb(response.body); const nodeStream = Readable.fromWeb(response.body);
nodeStream.pipe(res); nodeStream.pipe(res);
nodeStream.on('error', (err: Error) => { return new Promise((resolve, reject) => {
console.error('[Proxy] Stream error:', err); nodeStream.on('end', resolve);
if (!res.headersSent) { nodeStream.on('error', reject);
res.writeHead(502); res.on('close', () => {
res.end('Proxy stream error'); 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;
// 检查请求的范围是否已下载
if (end >= task.currentSize) {
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);
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) {
return existingTask;
}
const abortController = new AbortController();
const task: DownloadTask = {
currentSize: 0,
totalSize: 0,
contentType: 'audio/mpeg',
abortController,
promise: null,
};
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;
});
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 { }
} finally {
downloadTasks.delete(cacheFilePath);
}
})();
return task;
}
/**
* 主代理函数 - 智能处理缓存和 Range 请求
*/
async function proxyAndCache( async function proxyAndCache(
req: http.IncomingMessage, req: http.IncomingMessage,
res: http.ServerResponse, res: http.ServerResponse,
targetUrl: string, targetUrl: string,
cacheFilePath: string cacheFilePath: string,
cacheKey: string
): Promise<void> { ): Promise<void> {
const requestedRange = req.headers.range; const requestedRange = req.headers.range;
const isSeekRequest = requestedRange && !requestedRange.startsWith('bytes=0-');
// Check if already downloading // 检查是否有正在进行的后台下载
const downloadState = downloadingFiles.get(cacheFilePath); let task = downloadTasks.get(cacheFilePath);
if (downloadState) {
// Another request is already downloading this file
console.log(`[Proxy] File already downloading, current: ${downloadState.currentSize}/${downloadState.totalSize}`);
// For range requests, check if we can serve from partial cache if (task) {
if (requestedRange) { console.log(`[Proxy] Download in progress: ${task.currentSize}/${task.totalSize}`);
const range = parseRangeHeader(requestedRange, downloadState.totalSize);
if (range && range.end < downloadState.currentSize) {
// Requested range is fully downloaded, serve from cache
console.log(`[Proxy] Serving range from in-progress cache`);
const { start, end } = range; // 尝试从部分缓存中读取
const chunksize = (end - start) + 1; if (requestedRange && task.totalSize > 0) {
const range = parseRangeHeader(requestedRange, task.totalSize);
res.writeHead(206, { if (range) {
'Content-Range': `bytes ${start}-${end}/${downloadState.totalSize}`, // 检查请求的数据是否已下载
'Accept-Ranges': 'bytes', // 给一些缓冲区间(已下载部分的 95%
'Content-Length': chunksize, const safeEnd = Math.floor(task.currentSize * 0.95);
'Content-Type': 'audio/mpeg',
if (range.end < safeEnd && range.start < safeEnd) {
console.log(`[Proxy] Serving range ${range.start}-${range.end} from partial cache (downloaded: ${task.currentSize})`);
if (serveFromPartialCache(req, res, cacheFilePath, task)) {
return;
}
}
// 请求的数据还没下载到,直接代理这个 Range
console.log(`[Proxy] Range ${range.start}-${range.end} not cached yet (downloaded: ${task.currentSize}), 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 file = fs.createReadStream(cacheFilePath, { start, end }); const totalSize = parseInt(headResponse.headers.get('content-length') || '0', 10);
file.pipe(res); const contentType = headResponse.headers.get('content-type') || 'audio/mpeg';
return;
}
}
// Can't serve from cache, proxy directly // 直接代理当前的 Range 请求
await proxyWithoutCache(req, res, targetUrl); await proxyRangeDirect(req, res, targetUrl, totalSize, contentType);
return; return;
} }
// Check if this is a range request that doesn't start from 0 // 从头开始的请求:启动主下载任务并流式返回
if (requestedRange && !requestedRange.startsWith('bytes=0-')) {
// This is a seek request - we need to fetch total size first
// then decide whether to start a full download or just proxy
console.log(`[Proxy] Range request without cache: ${requestedRange}`);
await proxyWithoutCache(req, res, targetUrl);
return;
}
// Start a fresh download from the beginning
const headers: Record<string, string> = { const headers: Record<string, string> = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}; };
@@ -286,8 +512,10 @@ async function proxyAndCache(
if (!contentLength) { if (!contentLength) {
console.warn('[Proxy] No content-length, proxying without cache'); console.warn('[Proxy] No content-length, proxying without cache');
res.setHeader('Content-Type', contentType); res.writeHead(200, {
res.statusCode = 200; 'Content-Type': contentType,
'Accept-Ranges': 'bytes',
});
if (response.body) { if (response.body) {
// @ts-ignore // @ts-ignore
@@ -299,28 +527,29 @@ async function proxyAndCache(
return; return;
} }
// Setup caching // 设置下载任务
const tempPath = cacheFilePath + '.tmp'; const tempPath = getTempPath(cacheFilePath);
// Clean up any existing files // 清理旧文件
try { try {
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
if (fs.existsSync(cacheFilePath)) fs.unlinkSync(cacheFilePath); if (fs.existsSync(cacheFilePath)) fs.unlinkSync(cacheFilePath);
} catch (e) { } catch { }
console.error('[Proxy] Cleanup error:', e);
}
const fileStream = fs.createWriteStream(tempPath); const fileStream = fs.createWriteStream(tempPath);
downloadingFiles.set(cacheFilePath, { task = {
currentSize: 0, currentSize: 0,
totalSize: contentLength, totalSize: contentLength,
writeStream: fileStream contentType: contentType,
}); abortController: null,
promise: null,
};
downloadTasks.set(cacheFilePath, task);
console.log(`[Proxy] Starting download: ${cacheFilePath} (${contentLength} bytes)`); console.log(`[Proxy] Starting stream download: ${cacheFilePath} (${contentLength} bytes)`);
// Set response headers // 发送响应头
res.writeHead(200, { res.writeHead(200, {
'Content-Length': contentLength, 'Content-Length': contentLength,
'Content-Type': contentType, 'Content-Type': contentType,
@@ -329,7 +558,7 @@ async function proxyAndCache(
if (!response.body) { if (!response.body) {
res.end(); res.end();
downloadingFiles.delete(cacheFilePath); downloadTasks.delete(cacheFilePath);
return; return;
} }
@@ -337,26 +566,23 @@ async function proxyAndCache(
const nodeStream = Readable.fromWeb(response.body); const nodeStream = Readable.fromWeb(response.body);
const passThrough = new PassThrough(); const passThrough = new PassThrough();
// Track download progress // 跟踪下载进度
let downloadedBytes = 0;
passThrough.on('data', (chunk: Buffer) => { passThrough.on('data', (chunk: Buffer) => {
downloadedBytes += chunk.length; if (task) {
const state = downloadingFiles.get(cacheFilePath); task.currentSize += chunk.length;
if (state) {
state.currentSize = downloadedBytes;
} }
}); });
// Pipe to client // 流到客户端
passThrough.pipe(res); passThrough.pipe(res);
// Pipe to file // 流到文件
nodeStream.pipe(passThrough); nodeStream.pipe(passThrough);
nodeStream.pipe(fileStream); nodeStream.pipe(fileStream);
// Handle completion // 处理完成
const cleanup = (success: boolean, error?: Error) => { const cleanup = (success: boolean, error?: Error) => {
downloadingFiles.delete(cacheFilePath); downloadTasks.delete(cacheFilePath);
if (success && fs.existsSync(tempPath)) { if (success && fs.existsSync(tempPath)) {
try { try {
@@ -380,28 +606,104 @@ async function proxyAndCache(
} }
} else if (!success) { } else if (!success) {
console.error('[Proxy] Download failed:', error); console.error('[Proxy] Download failed:', error);
try { fs.unlinkSync(tempPath); } catch { } // 不删除临时文件,让后续请求可以继续
} }
}; };
fileStream.on('finish', () => cleanup(true)); fileStream.on('finish', () => cleanup(true));
fileStream.on('error', (err) => cleanup(false, err)); fileStream.on('error', (err) => cleanup(false, err));
nodeStream.on('error', (err: Error) => cleanup(false, err)); nodeStream.on('error', (err: Error) => {
cleanup(false, err);
if (!res.headersSent) {
res.writeHead(502);
res.end('Proxy stream error');
}
});
// Handle client disconnect // 客户端断开时不终止下载
res.on('close', () => { res.on('close', () => {
if (!res.writableEnded) { if (!res.writableEnded) {
console.log('[Proxy] Client disconnected during download'); console.log('[Proxy] Client disconnected, download continues in background');
// Don't cleanup - let the download continue in background
} }
}); });
} }
let persistCacheEnabled = true; 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() { export function cleanupCache() {
if (!persistCacheEnabled && CACHE_DIR && fs.existsSync(CACHE_DIR)) { if (!persistCacheEnabled && CACHE_DIR && fs.existsSync(CACHE_DIR)) {
console.log(`[Proxy] Cleaning up cache directory: ${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 { try {
fs.rmSync(CACHE_DIR, { recursive: true, force: true }); fs.rmSync(CACHE_DIR, { recursive: true, force: true });
console.log('[Proxy] Cache cleanup complete'); console.log('[Proxy] Cache cleanup complete');
@@ -411,10 +713,44 @@ export function cleanupCache() {
} }
} }
/**
* 清理过期的临时文件
*/
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) { export function startProxyServer(persistCache: boolean = true) {
persistCacheEnabled = persistCache; persistCacheEnabled = persistCache;
console.log(`[Proxy] Persist cache: ${persistCache}`); console.log(`[Proxy] Persist cache: ${persistCache}`);
// 定期清理临时文件
setInterval(cleanupTempFiles, 30 * 60 * 1000); // 每 30 分钟
const server = http.createServer(async (req, res) => { const server = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS'); res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
@@ -426,7 +762,6 @@ export function startProxyServer(persistCache: boolean = true) {
return; return;
} }
// Handle HEAD requests for range support detection
if (req.method === 'HEAD') { if (req.method === 'HEAD') {
res.setHeader('Accept-Ranges', 'bytes'); res.setHeader('Accept-Ranges', 'bytes');
res.statusCode = 200; res.statusCode = 200;
@@ -455,13 +790,13 @@ export function startProxyServer(persistCache: boolean = true) {
const cacheKey = `${source}:${id}:${quality}`; const cacheKey = `${source}:${id}:${quality}`;
const cacheFilePath = getCachePath(source, id, quality); const cacheFilePath = getCachePath(source, id, quality);
// 1. Check complete disk cache // 1. 检查完整缓存
if (isValidCacheFile(cacheFilePath)) { if (isValidCacheFile(cacheFilePath)) {
console.log(`[Proxy] Serving from complete cache: ${cacheFilePath}`); console.log(`[Proxy] Serving from complete cache: ${cacheFilePath}`);
const success = serveFromCache(req, res, cacheFilePath); const success = serveFromCache(req, res, cacheFilePath);
if (success) return; if (success) return;
// Cache invalid, clean up // 缓存无效,清理
console.warn('[Proxy] Cache file invalid, cleaning up...'); console.warn('[Proxy] Cache file invalid, cleaning up...');
try { try {
fs.unlinkSync(cacheFilePath); fs.unlinkSync(cacheFilePath);
@@ -469,7 +804,7 @@ export function startProxyServer(persistCache: boolean = true) {
} catch { } } catch { }
} }
// 2. Resolve URL // 2. 解析 URL
let playUrl: string | null = null; let playUrl: string | null = null;
const memCached = urlCache.get(cacheKey); const memCached = urlCache.get(cacheKey);
if (memCached && Date.now() < memCached.expiresAt) { if (memCached && Date.now() < memCached.expiresAt) {
@@ -487,15 +822,43 @@ export function startProxyServer(persistCache: boolean = true) {
return; return;
} }
// 3. Proxy & Cache // 3. 代理和缓存
const maxAttempts = 3;
let currentAttempt = 0;
let lastError: any = null;
while (currentAttempt < maxAttempts) {
try { try {
await proxyAndCache(req, res, playUrl, cacheFilePath); await proxyAndCache(req, res, playUrl, cacheFilePath, cacheKey);
break;
} catch (e: any) { } catch (e: any) {
console.warn(`[Proxy] Proxy error:`, e); lastError = e;
currentAttempt++;
console.warn(`[Proxy] Proxy error (Attempt ${currentAttempt}/${maxAttempts}):`, e);
if (currentAttempt < maxAttempts) {
console.log('[Proxy] Error occurred, refreshing URL from plugin...');
// 清除 URL 缓存
urlCache.delete(cacheKey);
// 获取新 URL
const newUrl = await fetchFreshUrl(source, id, quality);
if (newUrl) {
playUrl = newUrl;
continue;
} else {
console.error('[Proxy] Failed to refresh URL');
}
}
// 发送错误响应
if (!res.headersSent) { if (!res.headersSent) {
res.writeHead(e.statusCode || 502); res.writeHead(lastError?.statusCode || 502);
res.end('Proxy Error'); res.end('Proxy Error');
} }
break;
}
} }
} catch (err) { } catch (err) {
@@ -509,6 +872,7 @@ export function startProxyServer(persistCache: boolean = true) {
server.listen(PORT, '127.0.0.1', () => { server.listen(PORT, '127.0.0.1', () => {
ensureCacheDir(); ensureCacheDir();
cleanupTempFiles(); // 启动时清理
console.log(`[Proxy] Server running at http://127.0.0.1:${PORT}/music`); console.log(`[Proxy] Server running at http://127.0.0.1:${PORT}/music`);
console.log(`[Proxy] Cache dir: ${CACHE_DIR}`); console.log(`[Proxy] Cache dir: ${CACHE_DIR}`);
}); });

65
electron/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 });
}

View File

@@ -1,9 +1,26 @@
<template> <template>
<MainLayout /> <MainLayout />
<Settings v-if="showSettings" @close="showSettings = false" />
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, provide, onMounted } from 'vue';
import MainLayout from './layout/MainLayout.vue'; import MainLayout from './layout/MainLayout.vue';
import Settings from './components/Settings.vue';
const showSettings = ref(false);
// Provide to child components
provide('openSettings', () => { showSettings.value = true; });
// Apply saved theme on app startup
onMounted(async () => {
if (window.electronAPI?.settings) {
const settings = await window.electronAPI.settings.getAll();
document.documentElement.setAttribute('data-theme', settings.theme);
document.documentElement.style.setProperty('--color-accent', settings.accentColor);
}
});
</script> </script>
<style> <style>

View File

@@ -180,7 +180,7 @@ const formatTime = (seconds: number) => {
left: 0; left: 0;
width: 100%; width: 100%;
height: 80px; /* Established height */ height: 80px; /* Established height */
background-color: rgba(24, 24, 24, 0.95); /* Semi-transparent dark bg */ background-color: var(--color-bg-secondary);
backdrop-filter: blur(20px); backdrop-filter: blur(20px);
border-top: 1px solid var(--color-border); border-top: 1px solid var(--color-border);
display: flex; display: flex;
@@ -188,7 +188,8 @@ const formatTime = (seconds: number) => {
justify-content: space-between; justify-content: space-between;
padding: 0 24px; padding: 0 24px;
z-index: 1000; z-index: 1000;
box-shadow: 0 -4px 20px rgba(0,0,0,0.4); box-shadow: 0 -4px 20px rgba(0,0,0,0.15);
transition: var(--theme-transition);
} }
/* Animations */ /* Animations */
@@ -216,13 +217,16 @@ const formatTime = (seconds: number) => {
position: relative; position: relative;
width: 64px; width: 64px;
height: 64px; height: 64px;
min-width: 64px;
min-height: 64px;
flex-shrink: 0;
border-radius: 50%; border-radius: 50%;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
/* Vinyl Background Simulation or Image */ /* Dark background for vinyl effect */
background: radial-gradient(circle, #1a1a1a 30%, #333 31%, #111 32%, #181818 100%); background: #1a1a1a;
box-shadow: 0 4px 10px rgba(0,0,0,0.5); box-shadow: var(--shadow-md);
animation: spin 10s linear infinite; animation: spin 10s linear infinite;
animation-play-state: paused; animation-play-state: paused;
} }
@@ -231,7 +235,7 @@ const formatTime = (seconds: number) => {
animation-play-state: running; animation-play-state: running;
} }
/* Use the user specific path if available, or fallback to CSS vinyl look */ /* Vinyl overlay (Background) */
.vinyl-bg { .vinyl-bg {
position: absolute; position: absolute;
top: 0; top: 0;
@@ -239,27 +243,30 @@ const formatTime = (seconds: number) => {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 50%; border-radius: 50%;
background-image: url('@/assets/miniYinyl.png'); /* User requested path */ background-image: url('https://s5.music.126.net/static_public/68aea63daca57500bb3fb4b6_68aea63daca57500bb3fb4b7/public/assets/img/play/miniVinyl.png');
background-size: cover; background-size: cover;
opacity: 1; opacity: 1;
pointer-events: none; pointer-events: none;
z-index: 2; z-index: 1;
} }
/* Album art (Foreground) */
.album-art { .album-art {
width: 51px; width: 42px;
height: 51px; height: 42px;
border-radius: 50%; border-radius: 50%;
object-fit: cover; object-fit: cover;
z-index: 1; z-index: 10;
position: relative; /* Ensure z-index applies */
} }
.album-placeholder { .album-placeholder {
width: 51px; width: 42px;
height: 51px; height: 42px;
border-radius: 50%; border-radius: 50%;
background: #333; background: var(--color-bg-tertiary);
z-index: 1; z-index: 10;
position: relative; /* Ensure z-index applies */
} }
@keyframes spin { @keyframes spin {

View File

@@ -0,0 +1,680 @@
<template>
<Transition name="fade">
<div class="settings-overlay" v-if="isLoaded">
<div class="settings-container">
<!-- Header -->
<div class="settings-header">
<h1 class="settings-title">设置</h1>
<button class="close-btn" @click="$emit('close')">
<Icon icon="lucide:x" class="close-icon" />
</button>
</div>
<div class="settings-body">
<!-- Left Sidebar -->
<nav class="settings-nav">
<div
v-for="category in categories"
:key="category.id"
class="nav-item"
:class="{ active: activeCategory === category.id }"
@click="activeCategory = category.id"
>
<Icon :icon="category.icon" class="nav-icon" />
<span>{{ category.name }}</span>
</div>
</nav>
<!-- Right Content -->
<div class="settings-content">
<!-- 存储设置 -->
<div v-if="activeCategory === 'storage'" class="section">
<h2 class="section-title">存储设置</h2>
<!-- 缓存开关 -->
<div class="setting-item">
<div class="setting-info">
<div class="setting-label">缓存音乐到本地</div>
<div class="setting-desc">开启后将在本地保存播放过的音乐加快加载速度</div>
</div>
<div class="setting-control">
<label class="toggle-switch" :class="{ 'no-transition': !enableTransition }">
<input type="checkbox" v-model="settings.persistCache" @change="onCacheToggle" />
<span class="toggle-slider"></span>
</label>
</div>
</div>
<!-- 缓存位置 -->
<div class="setting-item">
<div class="setting-info">
<div class="setting-label">缓存位置</div>
<div class="setting-desc path-text">{{ cacheInfo.path || '加载中...' }}</div>
</div>
<div class="setting-control">
<button class="action-btn" @click="openCacheFolder">
<Icon icon="lucide:folder-open" />
打开目录
</button>
</div>
</div>
<!-- 缓存大小 -->
<div class="setting-item">
<div class="setting-info">
<div class="setting-label">已占用空间</div>
<div class="setting-desc">{{ cacheInfo.size || '计算中...' }}</div>
</div>
<div class="setting-control">
<button class="action-btn danger" @click="clearCache">
<Icon icon="lucide:trash-2" />
清理缓存
</button>
</div>
</div>
</div>
<!-- 外观设置 -->
<div v-else-if="activeCategory === 'appearance'" class="section">
<h2 class="section-title">外观设置</h2>
<!-- 亮暗模式 -->
<div class="setting-item">
<div class="setting-info">
<div class="setting-label">主题模式</div>
<div class="setting-desc">选择深色或浅色主题</div>
</div>
<div class="setting-control">
<div class="theme-toggle">
<button
class="theme-btn"
:class="{ active: appearance.theme === 'dark' }"
@click="setTheme('dark')"
>
<Icon icon="lucide:moon" />
深色
</button>
<button
class="theme-btn"
:class="{ active: appearance.theme === 'light' }"
@click="setTheme('light')"
>
<Icon icon="lucide:sun" />
浅色
</button>
</div>
</div>
</div>
<!-- 主题色 -->
<div class="setting-item">
<div class="setting-info">
<div class="setting-label">主题色</div>
<div class="setting-desc">选择你喜欢的强调色</div>
</div>
<div class="setting-control">
<div class="color-swatches">
<button
v-for="color in accentColors"
:key="color.value"
class="color-swatch"
:class="{ active: appearance.accentColor === color.value }"
:style="{ '--swatch-color': color.value }"
:title="color.name"
@click="setAccentColor(color.value)"
>
<Icon v-if="appearance.accentColor === color.value" icon="lucide:check" class="check-icon" />
</button>
</div>
</div>
</div>
</div>
<!-- 播放设置 -->
<div v-else-if="activeCategory === 'playback'" class="section">
<h2 class="section-title">播放设置</h2>
<div class="placeholder-content">
<Icon icon="lucide:headphones" class="placeholder-icon" />
<p>音质淡入淡出等设置即将推出</p>
</div>
</div>
<!-- 快捷键 -->
<div v-else-if="activeCategory === 'shortcuts'" class="section">
<h2 class="section-title">快捷键</h2>
<div class="placeholder-content">
<Icon icon="lucide:keyboard" class="placeholder-icon" />
<p>自定义快捷键即将推出</p>
</div>
</div>
<!-- 关于 -->
<div v-else-if="activeCategory === 'about'" class="section">
<h2 class="section-title">关于</h2>
<div class="about-content">
<div class="app-logo">🎶</div>
<h3>QZ Music</h3>
<p class="version">版本 1.0.0</p>
<p class="copyright">© 2024 QZ Music Team</p>
</div>
</div>
</div>
</div>
</div>
</div>
</Transition>
</template>
<script setup lang="ts">
import { ref, reactive, onBeforeMount, nextTick } from 'vue';
import { Icon } from '@iconify/vue';
defineEmits(['close']);
const categories = [
{ id: 'storage', name: '存储', icon: 'lucide:hard-drive' },
{ id: 'appearance', name: '外观', icon: 'lucide:palette' },
{ id: 'playback', name: '播放', icon: 'lucide:headphones' },
{ id: 'shortcuts', name: '快捷键', icon: 'lucide:keyboard' },
{ id: 'about', name: '关于', icon: 'lucide:info' },
];
const accentColors = [
{ name: '红色', value: '#ec4141' },
{ name: '橙色', value: '#f97316' },
{ name: '金色', value: '#eab308' },
{ name: '绿色', value: '#22c55e' },
{ name: '青色', value: '#06b6d4' },
{ name: '蓝色', value: '#3b82f6' },
{ name: '紫色', value: '#8b5cf6' },
{ name: '粉色', value: '#ec4899' },
];
const activeCategory = ref('storage');
const isLoaded = ref(false);
const enableTransition = ref(false);
const settings = reactive({
persistCache: true,
});
const appearance = reactive({
theme: 'dark' as 'dark' | 'light',
accentColor: '#ec4141',
});
const cacheInfo = reactive({
path: '',
size: '',
});
const loadCacheInfo = async () => {
if (window.electronAPI) {
const info = await window.electronAPI.getCacheInfo();
cacheInfo.path = info.path;
cacheInfo.size = info.size;
settings.persistCache = info.persistCache;
}
};
const loadAppearance = async () => {
if (window.electronAPI?.settings) {
const allSettings = await window.electronAPI.settings.getAll();
appearance.theme = allSettings.theme;
appearance.accentColor = allSettings.accentColor;
applyTheme(appearance.theme);
applyAccentColor(appearance.accentColor);
}
};
const applyTheme = (theme: 'dark' | 'light') => {
document.documentElement.setAttribute('data-theme', theme);
};
const applyAccentColor = (color: string) => {
document.documentElement.style.setProperty('--color-accent', color);
};
const setTheme = async (theme: 'dark' | 'light') => {
appearance.theme = theme;
applyTheme(theme);
if (window.electronAPI?.settings) {
await window.electronAPI.settings.setTheme(theme);
}
};
const setAccentColor = async (color: string) => {
appearance.accentColor = color;
applyAccentColor(color);
if (window.electronAPI?.settings) {
await window.electronAPI.settings.setAccentColor(color);
}
};
const onCacheToggle = async () => {
if (window.electronAPI) {
await window.electronAPI.setCachePersist(settings.persistCache);
}
};
const openCacheFolder = async () => {
if (window.electronAPI) {
await window.electronAPI.openCacheFolder();
}
};
const clearCache = async () => {
if (window.electronAPI) {
await window.electronAPI.clearCache();
await loadCacheInfo();
}
};
// Load settings BEFORE mount to avoid visual flicker
onBeforeMount(async () => {
await Promise.all([loadCacheInfo(), loadAppearance()]);
isLoaded.value = true;
// Enable transition after initial render
nextTick(() => {
setTimeout(() => {
enableTransition.value = true;
}, 50);
});
});
</script>
<style scoped>
/* Fade transition */
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.settings-overlay {
position: fixed;
inset: 0;
background-color: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(8px);
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
}
.settings-container {
width: 100%;
height: 100%;
background-color: var(--color-bg-primary);
display: flex;
flex-direction: column;
overflow: hidden;
}
.settings-header {
height: 64px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
border-bottom: 1px solid var(--color-border);
flex-shrink: 0;
-webkit-app-region: drag;
}
.settings-title {
font-size: var(--font-size-xl);
font-weight: 600;
color: var(--color-text-primary);
}
.close-btn {
-webkit-app-region: no-drag;
width: 40px;
height: 40px;
border-radius: var(--radius-md);
display: flex;
align-items: center;
justify-content: center;
background: transparent;
border: 1px solid var(--color-border);
color: var(--color-text-secondary);
cursor: pointer;
transition: all var(--transition-base);
}
.close-btn:hover {
background-color: var(--color-bg-tertiary);
color: var(--color-text-primary);
border-color: var(--color-text-muted);
}
.close-icon {
width: 20px;
height: 20px;
}
.settings-body {
flex: 1;
display: flex;
overflow: hidden;
}
/* Left Navigation */
.settings-nav {
width: 200px;
padding: 20px 12px;
background-color: var(--color-bg-secondary);
border-right: 1px solid var(--color-border);
flex-shrink: 0;
}
.nav-item {
display: flex;
align-items: center;
gap: 12px;
padding: 14px 16px;
margin-bottom: 4px;
border-radius: var(--radius-lg);
color: var(--color-text-secondary);
cursor: pointer;
transition: all var(--transition-base);
}
.nav-item:hover {
background-color: var(--color-bg-tertiary);
color: var(--color-text-primary);
}
.nav-item.active {
background-color: var(--color-accent-soft);
color: var(--color-accent);
}
.nav-icon {
width: 20px;
height: 20px;
flex-shrink: 0;
}
/* Right Content */
.settings-content {
flex: 1;
padding: 32px 48px;
overflow-y: auto;
}
.section-title {
font-size: var(--font-size-lg);
font-weight: 600;
color: var(--color-text-primary);
margin-bottom: 24px;
padding-bottom: 12px;
border-bottom: 1px solid var(--color-border);
}
/* Setting Item */
.setting-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 0;
border-bottom: 1px solid var(--color-border);
}
.setting-info {
flex: 1;
}
.setting-label {
font-size: var(--font-size-base);
color: var(--color-text-primary);
margin-bottom: 6px;
}
.setting-desc {
font-size: var(--font-size-sm);
color: var(--color-text-muted);
}
.setting-desc.path-text {
font-family: monospace;
background-color: var(--color-bg-tertiary);
padding: 4px 8px;
border-radius: var(--radius-sm);
display: inline-block;
max-width: 400px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.setting-control {
margin-left: 24px;
}
/* Toggle Switch */
.toggle-switch {
position: relative;
display: inline-block;
width: 48px;
height: 26px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
inset: 0;
background-color: var(--color-bg-tertiary);
border-radius: 26px;
transition: var(--transition-base);
}
.toggle-slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 3px;
background-color: var(--color-text-secondary);
border-radius: 50%;
transition: var(--transition-base);
}
/* Disable transition on initial load */
.toggle-switch.no-transition .toggle-slider,
.toggle-switch.no-transition .toggle-slider:before {
transition: none;
}
input:checked + .toggle-slider {
background-color: var(--color-accent);
}
input:checked + .toggle-slider:before {
transform: translateX(22px);
background-color: white;
}
/* Action Button */
.action-btn {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 16px;
border-radius: var(--radius-md);
background-color: var(--color-bg-tertiary);
color: var(--color-text-primary);
border: 1px solid var(--color-border);
cursor: pointer;
font-size: var(--font-size-sm);
transition: all var(--transition-base);
}
.action-btn:hover {
background-color: var(--color-bg-elevated);
border-color: var(--color-text-muted);
}
.action-btn.danger {
color: #ff6b6b;
}
.action-btn.danger:hover {
background-color: rgba(255, 107, 107, 0.1);
border-color: #ff6b6b;
}
/* Placeholder */
.placeholder-content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 80px 0;
color: var(--color-text-muted);
}
.placeholder-icon {
width: 64px;
height: 64px;
margin-bottom: 16px;
opacity: 0.5;
}
/* About */
.about-content {
display: flex;
flex-direction: column;
align-items: center;
padding: 60px 0;
text-align: center;
}
.app-logo {
width: 80px;
height: 80px;
background: linear-gradient(135deg, #ec4141, #ff6b6b);
border-radius: var(--radius-xl);
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
margin-bottom: 20px;
box-shadow: var(--shadow-lg);
}
.about-content h3 {
font-size: var(--font-size-2xl);
color: var(--color-text-primary);
margin-bottom: 8px;
}
.version {
color: var(--color-text-secondary);
margin-bottom: 4px;
}
.copyright {
color: var(--color-text-muted);
font-size: var(--font-size-sm);
}
/* Scrollbar */
.settings-content::-webkit-scrollbar {
width: 6px;
}
.settings-content::-webkit-scrollbar-track {
background: transparent;
}
.settings-content::-webkit-scrollbar-thumb {
background: var(--color-border-light);
border-radius: 3px;
}
.settings-content::-webkit-scrollbar-thumb:hover {
background: var(--color-text-muted);
}
/* Theme Toggle */
.theme-toggle {
display: flex;
gap: 8px;
background-color: var(--color-bg-tertiary);
padding: 4px;
border-radius: var(--radius-md);
}
.theme-btn {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 16px;
border-radius: var(--radius-sm);
background: transparent;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
font-size: var(--font-size-sm);
transition: all 0.2s ease;
}
.theme-btn:hover {
color: var(--color-text-primary);
}
.theme-btn.active {
background-color: var(--color-bg-primary);
color: var(--color-accent);
box-shadow: var(--shadow-sm);
}
/* Color Swatches */
.color-swatches {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.color-swatch {
width: 36px;
height: 36px;
border-radius: var(--radius-full);
border: 3px solid transparent;
background-color: var(--swatch-color);
cursor: pointer;
position: relative;
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
}
.color-swatch:hover {
transform: scale(1.1);
}
.color-swatch.active {
box-shadow: 0 0 16px var(--swatch-color);
}
.check-icon {
width: 18px;
height: 18px;
color: white;
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
}
</style>

View File

@@ -104,7 +104,7 @@ const togglePlaylists = () => {
flex-shrink: 0; flex-shrink: 0;
} }
/* 滚动条样式 */ /* 滚动条样式 - 默认隐藏,悬停时显示 */
.sidebar::-webkit-scrollbar { .sidebar::-webkit-scrollbar {
width: 6px; width: 6px;
} }
@@ -114,11 +114,16 @@ const togglePlaylists = () => {
} }
.sidebar::-webkit-scrollbar-thumb { .sidebar::-webkit-scrollbar-thumb {
background: var(--color-border-light); background: transparent;
border-radius: 3px; border-radius: 3px;
transition: background 0.2s ease;
} }
.sidebar::-webkit-scrollbar-thumb:hover { .sidebar:hover::-webkit-scrollbar-thumb {
background: var(--color-border-light);
}
.sidebar:hover::-webkit-scrollbar-thumb:hover {
background: var(--color-text-muted); background: var(--color-text-muted);
} }
@@ -184,7 +189,6 @@ const togglePlaylists = () => {
.nav-item:hover { .nav-item:hover {
background-color: var(--color-bg-tertiary); background-color: var(--color-bg-tertiary);
color: var(--color-text-primary); color: var(--color-text-primary);
transform: translateX(2px);
} }
.nav-item.active { .nav-item.active {
@@ -193,17 +197,6 @@ const togglePlaylists = () => {
font-weight: 500; font-weight: 500;
} }
.nav-item.active::before {
content: '';
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 3px;
height: 20px;
background-color: var(--color-accent);
border-radius: 0 2px 2px 0;
}
.nav-icon { .nav-icon {
width: 20px; width: 20px;
@@ -213,9 +206,6 @@ const togglePlaylists = () => {
transition: transform var(--transition-base); transition: transform var(--transition-base);
} }
.nav-item:hover .nav-icon {
transform: scale(1.1);
}
.nav-text { .nav-text {
font-size: var(--font-size-sm); font-size: var(--font-size-sm);

View File

@@ -24,7 +24,7 @@
<div class="right-controls"> <div class="right-controls">
<div class="app-actions"> <div class="app-actions">
<button class="action-btn ripple-btn" title="设置"> <button class="action-btn ripple-btn" title="设置" @click="openSettings">
<Icon icon="lucide:settings" class="action-icon" /> <Icon icon="lucide:settings" class="action-icon" />
</button> </button>
</div> </div>
@@ -49,7 +49,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'; import { ref, onMounted, onUnmounted, inject } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { Icon } from '@iconify/vue'; import { Icon } from '@iconify/vue';
@@ -59,6 +59,9 @@ const isMaximized = ref(false);
const goBack = () => router.back(); const goBack = () => router.back();
const goForward = () => router.forward(); const goForward = () => router.forward();
// Settings
const openSettings = inject<() => void>('openSettings', () => {});
// --- 窗口控制逻辑 --- // --- 窗口控制逻辑 ---
const handleMinimize = () => window.electronAPI?.minimizeWindow(); const handleMinimize = () => window.electronAPI?.minimizeWindow();
@@ -135,7 +138,6 @@ onUnmounted(() => {
color: var(--color-text-secondary); color: var(--color-text-secondary);
background-color: transparent; background-color: transparent;
border: 1px solid var(--color-border);
cursor: pointer; cursor: pointer;
position: relative; position: relative;
@@ -151,7 +153,6 @@ onUnmounted(() => {
.nav-btn:hover, .nav-btn:hover,
.action-btn:hover { .action-btn:hover {
background-color: var(--color-bg-tertiary); background-color: var(--color-bg-tertiary);
border-color: var(--color-text-muted);
color: var(--color-text-primary); color: var(--color-text-primary);
} }

View File

@@ -1,26 +1,11 @@
:root { :root {
/* Colors - 网易云风格配色 */ /* Theme transition */
--color-bg-primary: #121212; --theme-transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease, box-shadow 0.3s ease;
--color-bg-secondary: #181818;
--color-bg-tertiary: #282828;
--color-bg-elevated: #2a2a2a;
--color-text-primary: #ffffff;
--color-text-secondary: #b3b3b3;
--color-text-muted: #737373;
/* Dynamic accent color (set via JS) */
--color-accent: #ec4141; --color-accent: #ec4141;
--color-accent-hover: #ff5555; --color-accent-hover: color-mix(in srgb, var(--color-accent) 85%, white);
--color-accent-soft: rgba(236, 65, 65, 0.1); --color-accent-soft: color-mix(in srgb, var(--color-accent) 10%, transparent);
--color-border: #2a2a2a;
--color-border-light: #3a3a3a;
/* Shadows - 柔和阴影效果 */
--shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.12);
--shadow-md: 0 4px 16px rgba(0, 0, 0, 0.16);
--shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.24);
--shadow-elevated: 0 12px 48px rgba(0, 0, 0, 0.32);
/* Typography */ /* Typography */
--font-family-base: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; --font-family-base: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
@@ -31,7 +16,7 @@
--font-size-xl: 1.25rem; --font-size-xl: 1.25rem;
--font-size-2xl: 1.5rem; --font-size-2xl: 1.5rem;
/* Spacing & Radius - 网易云风格大圆角 */ /* Spacing & Radius */
--radius-sm: 8px; --radius-sm: 8px;
--radius-md: 12px; --radius-md: 12px;
--radius-lg: 20px; --radius-lg: 20px;
@@ -47,3 +32,59 @@
--transition-base: 0.25s ease; --transition-base: 0.25s ease;
--transition-slow: 0.35s ease; --transition-slow: 0.35s ease;
} }
/* Dark Theme (default) */
:root,
[data-theme="dark"] {
--color-bg-primary: #121212;
--color-bg-secondary: #181818;
--color-bg-tertiary: #282828;
--color-bg-elevated: #2a2a2a;
--color-text-primary: #ffffff;
--color-text-secondary: #b3b3b3;
--color-text-muted: #737373;
--color-border: #2a2a2a;
--color-border-light: #3a3a3a;
--shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.12);
--shadow-md: 0 4px 16px rgba(0, 0, 0, 0.16);
--shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.24);
--shadow-elevated: 0 12px 48px rgba(0, 0, 0, 0.32);
}
/* Light Theme */
[data-theme="light"] {
--color-bg-primary: #ffffff;
--color-bg-secondary: rgba(40, 50, 72, 0.03);
--color-bg-tertiary: #ebebeb;
--color-bg-elevated: #e0e0e0;
--color-text-primary: #1a1a1a;
--color-text-secondary: #5c5c5c;
--color-text-muted: #8c8c8c;
--color-border: #e0e0e0;
--color-border-light: #d0d0d0;
--shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.06);
--shadow-md: 0 4px 16px rgba(0, 0, 0, 0.08);
--shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.12);
--shadow-elevated: 0 12px 48px rgba(0, 0, 0, 0.16);
}
/* Apply theme transition to common elements */
body,
.sidebar,
.topbar,
.settings-overlay,
.settings-container,
.settings-nav,
.settings-content,
.nav-item,
.setting-item,
.action-btn,
.toggle-slider {
transition: var(--theme-transition);
}

View File

@@ -16,6 +16,20 @@ export interface IElectronAPI {
plugin: { plugin: {
call: (pluginId: string, method: string, args: any[]) => Promise<any>; call: (pluginId: string, method: string, args: any[]) => Promise<any>;
}; };
// Cache Control
getCacheInfo: () => Promise<{ path: string; size: string; persistCache: boolean }>;
setCachePersist: (persist: boolean) => Promise<void>;
openCacheFolder: () => Promise<void>;
clearCache: () => Promise<void>;
// Settings
settings: {
getAll: () => Promise<{ persistCache: boolean; theme: 'dark' | 'light'; accentColor: string }>;
set: (settings: Partial<{ persistCache: boolean; theme: 'dark' | 'light'; accentColor: string }>) => Promise<any>;
getTheme: () => Promise<'dark' | 'light'>;
setTheme: (theme: 'dark' | 'light') => Promise<void>;
getAccentColor: () => Promise<string>;
setAccentColor: (color: string) => Promise<void>;
};
} }
declare global { declare global {