2026-06-07 00:02:14 +08:00
|
|
|
import http from 'node:http';
|
|
|
|
|
import { Readable, type Writable } from 'node:stream';
|
|
|
|
|
import fs from 'node:fs';
|
|
|
|
|
import path from 'node:path';
|
2026-02-04 10:30:28 +08:00
|
|
|
import { app } from 'electron';
|
2026-06-07 00:02:14 +08:00
|
|
|
import { PluginSystem } from './pluginSystem';
|
2026-02-07 10:56:47 +08:00
|
|
|
import { loadSettings } from './settingsStore';
|
2026-02-04 10:30:28 +08:00
|
|
|
|
|
|
|
|
const PORT = 5266;
|
2026-06-07 00:02:14 +08:00
|
|
|
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
|
|
|
|
|
const URL_TTL_MS = 50 * 60 * 1000;
|
|
|
|
|
const STALE_TEMP_TTL_MS = 60 * 60 * 1000;
|
|
|
|
|
const MAX_ACTIVE_DOWNLOADS = 1;
|
|
|
|
|
const MIN_VALID_CACHE_SIZE = 1024;
|
2026-02-07 10:56:47 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
let CACHE_DIR = '';
|
|
|
|
|
let persistCacheEnabled = true;
|
|
|
|
|
let serverInstance: http.Server | null = null;
|
|
|
|
|
let cleanupTimer: ReturnType<typeof setInterval> | null = null;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
|
|
|
|
interface CacheEntry {
|
|
|
|
|
url: string;
|
|
|
|
|
expiresAt: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface CacheMetadata {
|
|
|
|
|
totalSize: number;
|
|
|
|
|
contentType: string;
|
|
|
|
|
complete: boolean;
|
|
|
|
|
createdAt: number;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-04 14:14:40 +08:00
|
|
|
interface DownloadTask {
|
2026-06-07 00:02:14 +08:00
|
|
|
cacheFilePath: string;
|
|
|
|
|
tempPath: string;
|
2026-02-04 10:30:28 +08:00
|
|
|
currentSize: number;
|
|
|
|
|
totalSize: number;
|
2026-02-04 14:14:40 +08:00
|
|
|
contentType: string;
|
2026-06-07 00:02:14 +08:00
|
|
|
abortController: AbortController;
|
|
|
|
|
promise: Promise<void>;
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
interface RangeValue {
|
|
|
|
|
start: number;
|
|
|
|
|
end: number;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class ProxyHttpError extends Error {
|
|
|
|
|
constructor(
|
|
|
|
|
readonly statusCode: number,
|
|
|
|
|
message: string,
|
|
|
|
|
) {
|
|
|
|
|
super(message);
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const urlCache = new Map<string, CacheEntry>();
|
|
|
|
|
const pendingUrlResolves = new Map<string, Promise<string | null>>();
|
2026-02-04 14:14:40 +08:00
|
|
|
const downloadTasks = new Map<string, DownloadTask>();
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function ensureCacheDir(): string {
|
|
|
|
|
const settings = loadSettings();
|
|
|
|
|
const nextDir = settings.cachePath || path.join(app.getPath('userData'), 'cache');
|
|
|
|
|
|
|
|
|
|
if (CACHE_DIR !== nextDir) {
|
|
|
|
|
CACHE_DIR = nextDir;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!fs.existsSync(CACHE_DIR)) {
|
|
|
|
|
fs.mkdirSync(CACHE_DIR, { recursive: true });
|
|
|
|
|
console.log(`[Proxy] Created cache directory: ${CACHE_DIR}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return CACHE_DIR;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function refreshCacheDir(): string {
|
|
|
|
|
CACHE_DIR = '';
|
|
|
|
|
return ensureCacheDir();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function sanitizePart(value: string): string {
|
|
|
|
|
return value.replace(/[^a-z0-9._-]/gi, '_');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function getCachePath(source: string, id: string, quality: string): string {
|
2026-02-04 10:30:28 +08:00
|
|
|
const dir = ensureCacheDir();
|
2026-06-07 00:02:14 +08:00
|
|
|
return path.join(dir, `${sanitizePart(source)}-${sanitizePart(id)}-${sanitizePart(quality)}`);
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function getMetadataPath(cachePath: string): string {
|
2026-06-07 00:02:14 +08:00
|
|
|
return `${cachePath}.meta`;
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-02-04 14:14:40 +08:00
|
|
|
function getTempPath(cachePath: string): string {
|
2026-06-07 00:02:14 +08:00
|
|
|
return `${cachePath}.tmp`;
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
|
|
|
|
|
2026-02-04 10:30:28 +08:00
|
|
|
function readMetadata(cachePath: string): CacheMetadata | null {
|
|
|
|
|
try {
|
2026-06-07 00:02:14 +08:00
|
|
|
const metaPath = getMetadataPath(cachePath);
|
|
|
|
|
if (!fs.existsSync(metaPath)) return null;
|
|
|
|
|
return JSON.parse(fs.readFileSync(metaPath, 'utf-8')) as CacheMetadata;
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.warn('[Proxy] Failed to read cache metadata:', err);
|
|
|
|
|
return null;
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function writeMetadata(cachePath: string, metadata: CacheMetadata): void {
|
2026-02-04 10:30:28 +08:00
|
|
|
const metaPath = getMetadataPath(cachePath);
|
2026-06-07 00:02:14 +08:00
|
|
|
const tempMetaPath = `${metaPath}.tmp`;
|
|
|
|
|
fs.writeFileSync(tempMetaPath, JSON.stringify(metadata));
|
|
|
|
|
fs.renameSync(tempMetaPath, metaPath);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function removeFileIfExists(filePath: string): void {
|
2026-02-04 10:30:28 +08:00
|
|
|
try {
|
2026-06-07 00:02:14 +08:00
|
|
|
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.warn(`[Proxy] Failed to remove ${filePath}:`, err);
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function removeCacheFiles(cachePath: string): void {
|
|
|
|
|
removeFileIfExists(cachePath);
|
|
|
|
|
removeFileIfExists(getMetadataPath(cachePath));
|
|
|
|
|
removeFileIfExists(getTempPath(cachePath));
|
|
|
|
|
removeFileIfExists(`${getMetadataPath(cachePath)}.tmp`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function getCachedUrl(cacheKey: string): string | null {
|
|
|
|
|
const entry = urlCache.get(cacheKey);
|
|
|
|
|
if (!entry) return null;
|
|
|
|
|
|
|
|
|
|
if (Date.now() >= entry.expiresAt) {
|
|
|
|
|
urlCache.delete(cacheKey);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return entry.url;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function resolvePlayUrl(source: string, id: string, quality: string, forceRefresh = false): Promise<string | null> {
|
|
|
|
|
const cacheKey = `${source}:${id}:${quality}`;
|
|
|
|
|
|
|
|
|
|
if (!forceRefresh) {
|
|
|
|
|
const cached = getCachedUrl(cacheKey);
|
|
|
|
|
if (cached) return cached;
|
|
|
|
|
} else {
|
|
|
|
|
urlCache.delete(cacheKey);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const existing = pendingUrlResolves.get(cacheKey);
|
|
|
|
|
if (existing) return existing;
|
|
|
|
|
|
|
|
|
|
const promise = (async () => {
|
|
|
|
|
try {
|
|
|
|
|
const plugin = new PluginSystem(source);
|
|
|
|
|
const result = await plugin.getUrl(id, quality);
|
|
|
|
|
if (!result.success || !result.url) {
|
|
|
|
|
console.error(`[Proxy] Failed to resolve URL for ${cacheKey}:`, result.error);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
urlCache.set(cacheKey, {
|
2026-02-04 10:30:28 +08:00
|
|
|
url: result.url,
|
2026-06-07 00:02:14 +08:00
|
|
|
expiresAt: Date.now() + URL_TTL_MS,
|
2026-02-04 10:30:28 +08:00
|
|
|
});
|
|
|
|
|
return result.url;
|
2026-06-07 00:02:14 +08:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error(`[Proxy] URL resolve error for ${cacheKey}:`, err);
|
|
|
|
|
return null;
|
|
|
|
|
} finally {
|
|
|
|
|
pendingUrlResolves.delete(cacheKey);
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
pendingUrlResolves.set(cacheKey, promise);
|
|
|
|
|
return promise;
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function isValidCacheFile(cachePath: string): boolean {
|
2026-02-04 14:14:40 +08:00
|
|
|
try {
|
2026-06-07 00:02:14 +08:00
|
|
|
const metadata = readMetadata(cachePath);
|
|
|
|
|
if (!metadata?.complete || !fs.existsSync(cachePath)) return false;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const stat = fs.statSync(cachePath);
|
|
|
|
|
return stat.isFile() && stat.size === metadata.totalSize && stat.size > MIN_VALID_CACHE_SIZE;
|
2026-02-04 14:14:40 +08:00
|
|
|
} catch {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function parseRangeHeader(rangeHeader: string | undefined, fileSize: number): RangeValue | null {
|
|
|
|
|
if (!rangeHeader || fileSize <= 0) return null;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());
|
2026-02-04 10:30:28 +08:00
|
|
|
if (!match) return null;
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const [, rawStart, rawEnd] = match;
|
|
|
|
|
if (!rawStart && !rawEnd) return null;
|
|
|
|
|
|
|
|
|
|
let start: number;
|
|
|
|
|
let end: number;
|
|
|
|
|
|
|
|
|
|
if (!rawStart) {
|
|
|
|
|
const suffixLength = Number.parseInt(rawEnd, 10);
|
|
|
|
|
if (!Number.isFinite(suffixLength) || suffixLength <= 0) return null;
|
|
|
|
|
start = Math.max(fileSize - suffixLength, 0);
|
|
|
|
|
end = fileSize - 1;
|
|
|
|
|
} else {
|
|
|
|
|
start = Number.parseInt(rawStart, 10);
|
|
|
|
|
end = rawEnd ? Number.parseInt(rawEnd, 10) : fileSize - 1;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
|
|
|
|
|
if (start < 0 || start >= fileSize || end < start) return null;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
return {
|
|
|
|
|
start,
|
|
|
|
|
end: Math.min(end, fileSize - 1),
|
|
|
|
|
};
|
|
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function isSeekRange(rangeHeader: string | undefined): boolean {
|
|
|
|
|
if (!rangeHeader) return false;
|
|
|
|
|
const range = /^bytes=(\d*)-/.exec(rangeHeader.trim());
|
|
|
|
|
return !!range?.[1] && Number.parseInt(range[1], 10) > 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function sendError(res: http.ServerResponse, statusCode: number, message: string): void {
|
|
|
|
|
if (res.destroyed || res.writableEnded) return;
|
|
|
|
|
|
|
|
|
|
if (!res.headersSent) {
|
|
|
|
|
res.writeHead(statusCode, {
|
|
|
|
|
'Content-Type': 'text/plain; charset=utf-8',
|
|
|
|
|
'Cache-Control': 'no-store',
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
res.end(message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function setCommonHeaders(res: http.ServerResponse): void {
|
|
|
|
|
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
|
|
|
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
|
|
|
|
|
res.setHeader('Access-Control-Allow-Headers', 'Range, Content-Type');
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function serveFromCache(req: http.IncomingMessage, res: http.ServerResponse, filePath: string): boolean {
|
2026-02-04 14:14:40 +08:00
|
|
|
try {
|
|
|
|
|
const metadata = readMetadata(filePath);
|
2026-06-07 00:02:14 +08:00
|
|
|
if (!metadata) return false;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const fileSize = fs.statSync(filePath).size;
|
2026-02-04 14:14:40 +08:00
|
|
|
const range = parseRangeHeader(req.headers.range, fileSize);
|
2026-06-07 00:02:14 +08:00
|
|
|
const contentType = metadata.contentType || 'audio/mpeg';
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (req.method === 'HEAD') {
|
2026-02-04 14:14:40 +08:00
|
|
|
res.writeHead(200, {
|
|
|
|
|
'Content-Length': fileSize,
|
2026-06-07 00:02:14 +08:00
|
|
|
'Content-Type': contentType,
|
2026-02-04 14:14:40 +08:00
|
|
|
'Accept-Ranges': 'bytes',
|
2026-06-07 00:02:14 +08:00
|
|
|
'X-Proxy-Cache': 'HIT',
|
2026-02-04 14:14:40 +08:00
|
|
|
});
|
2026-06-07 00:02:14 +08:00
|
|
|
res.end();
|
|
|
|
|
return true;
|
|
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (req.headers.range && !range) {
|
|
|
|
|
res.writeHead(416, {
|
|
|
|
|
'Content-Range': `bytes */${fileSize}`,
|
|
|
|
|
'Accept-Ranges': 'bytes',
|
2026-02-04 14:14:40 +08:00
|
|
|
});
|
2026-06-07 00:02:14 +08:00
|
|
|
res.end();
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const streamRange = range || { start: 0, end: fileSize - 1 };
|
|
|
|
|
const statusCode = range ? 206 : 200;
|
|
|
|
|
const contentLength = streamRange.end - streamRange.start + 1;
|
|
|
|
|
const headers: http.OutgoingHttpHeaders = {
|
|
|
|
|
'Content-Length': contentLength,
|
|
|
|
|
'Content-Type': contentType,
|
|
|
|
|
'Accept-Ranges': 'bytes',
|
|
|
|
|
'X-Proxy-Cache': 'HIT',
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (range) {
|
|
|
|
|
headers['Content-Range'] = `bytes ${range.start}-${range.end}/${fileSize}`;
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
|
|
|
|
|
res.writeHead(statusCode, headers);
|
|
|
|
|
|
|
|
|
|
const fileStream = fs.createReadStream(filePath, streamRange);
|
|
|
|
|
fileStream.once('error', (err) => {
|
|
|
|
|
console.error('[Proxy] Cache read error:', err);
|
|
|
|
|
sendError(res, 500, 'Cache read error');
|
|
|
|
|
});
|
|
|
|
|
res.once('close', () => fileStream.destroy());
|
|
|
|
|
fileStream.pipe(res);
|
2026-02-04 14:14:40 +08:00
|
|
|
return true;
|
2026-06-07 00:02:14 +08:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error('[Proxy] Failed to serve cache:', err);
|
2026-02-04 14:14:40 +08:00
|
|
|
return false;
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function serveFromPartialCache(
|
2026-02-04 10:30:28 +08:00
|
|
|
req: http.IncomingMessage,
|
|
|
|
|
res: http.ServerResponse,
|
2026-06-07 00:02:14 +08:00
|
|
|
task: DownloadTask,
|
|
|
|
|
): boolean {
|
|
|
|
|
try {
|
|
|
|
|
if (!req.headers.range || task.totalSize <= 0 || !fs.existsSync(task.tempPath)) return false;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const range = parseRangeHeader(req.headers.range, task.totalSize);
|
|
|
|
|
if (!range) return false;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const actualSize = fs.statSync(task.tempPath).size;
|
|
|
|
|
if (range.end >= actualSize) return false;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-02-04 14:14:40 +08:00
|
|
|
res.writeHead(206, {
|
2026-06-07 00:02:14 +08:00
|
|
|
'Content-Range': `bytes ${range.start}-${range.end}/${task.totalSize}`,
|
2026-02-04 14:14:40 +08:00
|
|
|
'Accept-Ranges': 'bytes',
|
2026-06-07 00:02:14 +08:00
|
|
|
'Content-Length': range.end - range.start + 1,
|
|
|
|
|
'Content-Type': task.contentType || 'audio/mpeg',
|
|
|
|
|
'X-Proxy-Cache': 'PARTIAL',
|
2026-02-04 14:14:40 +08:00
|
|
|
});
|
2026-06-07 00:02:14 +08:00
|
|
|
|
|
|
|
|
const fileStream = fs.createReadStream(task.tempPath, range);
|
|
|
|
|
fileStream.once('error', (err) => {
|
|
|
|
|
console.error('[Proxy] Partial cache read error:', err);
|
|
|
|
|
sendError(res, 500, 'Partial cache read error');
|
2026-02-04 14:14:40 +08:00
|
|
|
});
|
2026-06-07 00:02:14 +08:00
|
|
|
res.once('close', () => fileStream.destroy());
|
|
|
|
|
fileStream.pipe(res);
|
|
|
|
|
return true;
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.warn('[Proxy] Failed to serve partial cache:', err);
|
|
|
|
|
return false;
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function writeChunk(stream: Writable, chunk: Buffer): Promise<void> {
|
|
|
|
|
if (stream.destroyed || stream.writableEnded) return;
|
|
|
|
|
if (stream.write(chunk)) return;
|
|
|
|
|
|
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
|
|
|
const onDrain = () => cleanup(resolve);
|
|
|
|
|
const onError = (err: Error) => cleanup(() => reject(err));
|
|
|
|
|
const cleanup = (done: () => void) => {
|
|
|
|
|
stream.off('drain', onDrain);
|
|
|
|
|
stream.off('error', onError);
|
|
|
|
|
done();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
stream.once('drain', onDrain);
|
|
|
|
|
stream.once('error', onError);
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
async function endWritable(stream: Writable): Promise<void> {
|
|
|
|
|
if (stream.destroyed || stream.writableEnded) return;
|
|
|
|
|
|
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
|
|
|
const onFinish = () => cleanup(resolve);
|
|
|
|
|
const onError = (err: Error) => cleanup(() => reject(err));
|
|
|
|
|
const cleanup = (done: () => void) => {
|
|
|
|
|
stream.off('finish', onFinish);
|
|
|
|
|
stream.off('error', onError);
|
|
|
|
|
done();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
stream.once('finish', onFinish);
|
|
|
|
|
stream.once('error', onError);
|
|
|
|
|
stream.end();
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function responseBodyToNodeStream(response: Response): Readable {
|
2026-02-04 10:30:28 +08:00
|
|
|
if (!response.body) {
|
2026-06-07 00:02:14 +08:00
|
|
|
throw new ProxyHttpError(502, 'Upstream response has no body');
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
return Readable.fromWeb(response.body as any);
|
|
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function buildUpstreamHeaders(range?: string): Record<string, string> {
|
|
|
|
|
const headers: Record<string, string> = {
|
|
|
|
|
'User-Agent': USER_AGENT,
|
|
|
|
|
'Accept': '*/*',
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (range) headers.Range = range;
|
|
|
|
|
return headers;
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
async function proxyDirect(
|
2026-02-04 14:14:40 +08:00
|
|
|
req: http.IncomingMessage,
|
|
|
|
|
res: http.ServerResponse,
|
2026-06-07 00:02:14 +08:00
|
|
|
targetUrl: string,
|
|
|
|
|
fallbackContentType = 'audio/mpeg',
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
const controller = new AbortController();
|
|
|
|
|
let completed = false;
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const abortIfClientGone = () => {
|
|
|
|
|
if (!completed) controller.abort();
|
|
|
|
|
};
|
|
|
|
|
res.once('close', abortIfClientGone);
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
try {
|
|
|
|
|
const response = await fetch(targetUrl, {
|
|
|
|
|
method: req.method === 'HEAD' ? 'HEAD' : 'GET',
|
|
|
|
|
headers: buildUpstreamHeaders(req.headers.range),
|
|
|
|
|
signal: controller.signal,
|
|
|
|
|
});
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (!response.ok && response.status !== 206) {
|
|
|
|
|
throw new ProxyHttpError(response.status, response.statusText || 'Upstream error');
|
2026-02-05 18:52:58 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const contentType = response.headers.get('content-type') || fallbackContentType;
|
|
|
|
|
const contentLength = response.headers.get('content-length');
|
|
|
|
|
const contentRange = response.headers.get('content-range');
|
|
|
|
|
const headers: http.OutgoingHttpHeaders = {
|
|
|
|
|
'Content-Type': contentType,
|
|
|
|
|
'Accept-Ranges': response.headers.get('accept-ranges') || 'bytes',
|
|
|
|
|
'X-Proxy-Cache': 'BYPASS',
|
|
|
|
|
};
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (contentLength) headers['Content-Length'] = contentLength;
|
|
|
|
|
if (contentRange) headers['Content-Range'] = contentRange;
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
res.writeHead(response.status === 206 ? 206 : 200, headers);
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (req.method === 'HEAD') {
|
|
|
|
|
completed = true;
|
|
|
|
|
res.end();
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const upstream = responseBodyToNodeStream(response);
|
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
|
|
|
upstream.once('error', reject);
|
|
|
|
|
upstream.once('end', resolve);
|
|
|
|
|
upstream.pipe(res);
|
2026-02-05 18:52:58 +08:00
|
|
|
});
|
2026-06-07 00:02:14 +08:00
|
|
|
completed = true;
|
|
|
|
|
} catch (err: any) {
|
|
|
|
|
if (err?.name === 'AbortError') return;
|
|
|
|
|
throw err;
|
|
|
|
|
} finally {
|
|
|
|
|
completed = true;
|
|
|
|
|
res.off('close', abortIfClientGone);
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function cancelDownloadsExcept(exceptPath: string): void {
|
|
|
|
|
for (const [cachePath, task] of downloadTasks) {
|
|
|
|
|
if (cachePath === exceptPath) continue;
|
|
|
|
|
|
|
|
|
|
console.log(`[Proxy] Cancelling stale download: ${cachePath}`);
|
|
|
|
|
task.abortController.abort();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (downloadTasks.size <= MAX_ACTIVE_DOWNLOADS) return;
|
|
|
|
|
|
|
|
|
|
for (const [cachePath, task] of downloadTasks) {
|
|
|
|
|
if (cachePath === exceptPath) continue;
|
|
|
|
|
task.abortController.abort();
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function createDownloadTask(targetUrl: string, cacheFilePath: string): DownloadTask {
|
2026-02-04 14:14:40 +08:00
|
|
|
const abortController = new AbortController();
|
2026-06-07 00:02:14 +08:00
|
|
|
const tempPath = getTempPath(cacheFilePath);
|
2026-02-04 14:14:40 +08:00
|
|
|
const task: DownloadTask = {
|
2026-06-07 00:02:14 +08:00
|
|
|
cacheFilePath,
|
|
|
|
|
tempPath,
|
2026-02-04 14:14:40 +08:00
|
|
|
currentSize: 0,
|
|
|
|
|
totalSize: 0,
|
|
|
|
|
contentType: 'audio/mpeg',
|
|
|
|
|
abortController,
|
2026-06-07 00:02:14 +08:00
|
|
|
promise: Promise.resolve(),
|
2026-02-04 14:14:40 +08:00
|
|
|
};
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
task.promise = downloadToCache(targetUrl, task).finally(() => {
|
|
|
|
|
if (downloadTasks.get(cacheFilePath) === task) {
|
2026-02-04 14:14:40 +08:00
|
|
|
downloadTasks.delete(cacheFilePath);
|
|
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
});
|
2026-02-04 14:14:40 +08:00
|
|
|
|
|
|
|
|
return task;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function startBackgroundDownload(targetUrl: string, cacheFilePath: string): DownloadTask {
|
|
|
|
|
const existing = downloadTasks.get(cacheFilePath);
|
|
|
|
|
if (existing) return existing;
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
cancelDownloadsExcept(cacheFilePath);
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const task = createDownloadTask(targetUrl, cacheFilePath);
|
|
|
|
|
downloadTasks.set(cacheFilePath, task);
|
|
|
|
|
task.promise.catch((err) => {
|
|
|
|
|
if (err?.name !== 'AbortError') {
|
|
|
|
|
console.warn('[Proxy] Background cache download failed:', err);
|
2026-02-06 17:01:45 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
});
|
|
|
|
|
return task;
|
2026-02-06 17:01:45 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
async function downloadToCache(targetUrl: string, task: DownloadTask): Promise<void> {
|
|
|
|
|
removeFileIfExists(task.tempPath);
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const response = await fetch(targetUrl, {
|
|
|
|
|
method: 'GET',
|
|
|
|
|
headers: buildUpstreamHeaders(),
|
|
|
|
|
signal: task.abortController.signal,
|
|
|
|
|
});
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new ProxyHttpError(response.status, response.statusText || 'Cache download failed');
|
|
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const contentLength = Number.parseInt(response.headers.get('content-length') || '0', 10);
|
|
|
|
|
if (!contentLength) {
|
|
|
|
|
console.warn('[Proxy] Upstream has no content-length; skipping cache');
|
2026-02-04 10:30:28 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
task.totalSize = contentLength;
|
|
|
|
|
task.contentType = response.headers.get('content-type') || 'audio/mpeg';
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const upstream = responseBodyToNodeStream(response);
|
|
|
|
|
const fileStream = fs.createWriteStream(task.tempPath);
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
console.log(`[Proxy] Cache download started: ${task.cacheFilePath} (${contentLength} bytes)`);
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
try {
|
|
|
|
|
for await (const chunk of upstream) {
|
|
|
|
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
|
|
|
|
|
task.currentSize += buffer.length;
|
|
|
|
|
await writeChunk(fileStream, buffer);
|
|
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
await endWritable(fileStream);
|
|
|
|
|
finalizeCacheFile(task);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
fileStream.destroy();
|
|
|
|
|
removeFileIfExists(task.tempPath);
|
|
|
|
|
throw err;
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function finalizeCacheFile(task: DownloadTask): void {
|
|
|
|
|
const stat = fs.statSync(task.tempPath);
|
|
|
|
|
if (stat.size !== task.totalSize || stat.size <= MIN_VALID_CACHE_SIZE) {
|
|
|
|
|
removeFileIfExists(task.tempPath);
|
|
|
|
|
throw new Error(`Incomplete cache file: ${stat.size}/${task.totalSize}`);
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
removeFileIfExists(task.cacheFilePath);
|
|
|
|
|
fs.renameSync(task.tempPath, task.cacheFilePath);
|
|
|
|
|
writeMetadata(task.cacheFilePath, {
|
|
|
|
|
totalSize: task.totalSize,
|
|
|
|
|
contentType: task.contentType,
|
|
|
|
|
complete: true,
|
|
|
|
|
createdAt: Date.now(),
|
|
|
|
|
});
|
|
|
|
|
console.log(`[Proxy] Cache download complete: ${task.cacheFilePath}`);
|
2026-02-05 18:52:58 +08:00
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-02-05 18:52:58 +08:00
|
|
|
async function streamAndCache(
|
2026-06-07 00:02:14 +08:00
|
|
|
req: http.IncomingMessage,
|
2026-02-05 18:52:58 +08:00
|
|
|
res: http.ServerResponse,
|
|
|
|
|
targetUrl: string,
|
|
|
|
|
cacheFilePath: string,
|
|
|
|
|
): Promise<void> {
|
2026-06-07 00:02:14 +08:00
|
|
|
cancelDownloadsExcept(cacheFilePath);
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const existingTask = downloadTasks.get(cacheFilePath);
|
|
|
|
|
if (existingTask) {
|
|
|
|
|
if (serveFromPartialCache(req, res, existingTask)) return;
|
|
|
|
|
await proxyDirect(req, res, targetUrl, existingTask.contentType);
|
|
|
|
|
return;
|
2026-02-06 17:01:45 +08:00
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const controller = new AbortController();
|
|
|
|
|
const response = await fetch(targetUrl, {
|
|
|
|
|
method: 'GET',
|
|
|
|
|
headers: buildUpstreamHeaders(),
|
|
|
|
|
signal: controller.signal,
|
|
|
|
|
});
|
|
|
|
|
|
2026-02-04 10:30:28 +08:00
|
|
|
if (!response.ok) {
|
2026-06-07 00:02:14 +08:00
|
|
|
throw new ProxyHttpError(response.status, response.statusText || 'Upstream error');
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const contentLength = Number.parseInt(response.headers.get('content-length') || '0', 10);
|
2026-02-04 10:30:28 +08:00
|
|
|
const contentType = response.headers.get('content-type') || 'audio/mpeg';
|
|
|
|
|
|
|
|
|
|
if (!contentLength) {
|
2026-06-07 00:02:14 +08:00
|
|
|
console.warn('[Proxy] Upstream has no content-length; streaming without cache');
|
|
|
|
|
const upstream = responseBodyToNodeStream(response);
|
|
|
|
|
let completed = false;
|
|
|
|
|
const abortIfClientGone = () => {
|
|
|
|
|
if (!completed) {
|
|
|
|
|
controller.abort();
|
|
|
|
|
upstream.destroy();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
res.once('close', abortIfClientGone);
|
2026-02-04 14:14:40 +08:00
|
|
|
res.writeHead(200, {
|
|
|
|
|
'Content-Type': contentType,
|
|
|
|
|
'Accept-Ranges': 'bytes',
|
2026-06-07 00:02:14 +08:00
|
|
|
'X-Proxy-Cache': 'BYPASS',
|
2026-02-04 14:14:40 +08:00
|
|
|
});
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
try {
|
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
|
|
|
upstream.once('error', reject);
|
|
|
|
|
upstream.once('end', resolve);
|
|
|
|
|
upstream.pipe(res);
|
2026-02-06 17:01:45 +08:00
|
|
|
});
|
2026-06-07 00:02:14 +08:00
|
|
|
completed = true;
|
|
|
|
|
} finally {
|
|
|
|
|
completed = true;
|
|
|
|
|
res.off('close', abortIfClientGone);
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-04 14:14:40 +08:00
|
|
|
const tempPath = getTempPath(cacheFilePath);
|
2026-06-07 00:02:14 +08:00
|
|
|
removeCacheFiles(cacheFilePath);
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-02-05 18:52:58 +08:00
|
|
|
const task: DownloadTask = {
|
2026-06-07 00:02:14 +08:00
|
|
|
cacheFilePath,
|
|
|
|
|
tempPath,
|
2026-02-04 10:30:28 +08:00
|
|
|
currentSize: 0,
|
|
|
|
|
totalSize: contentLength,
|
2026-06-07 00:02:14 +08:00
|
|
|
contentType,
|
2026-02-06 17:01:45 +08:00
|
|
|
abortController: controller,
|
2026-06-07 00:02:14 +08:00
|
|
|
promise: Promise.resolve(),
|
2026-02-04 14:14:40 +08:00
|
|
|
};
|
|
|
|
|
downloadTasks.set(cacheFilePath, task);
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const upstream = responseBodyToNodeStream(response);
|
|
|
|
|
const fileStream = fs.createWriteStream(tempPath);
|
|
|
|
|
let clientConnected = true;
|
|
|
|
|
let cacheWritable = true;
|
|
|
|
|
|
|
|
|
|
res.once('close', () => {
|
|
|
|
|
clientConnected = false;
|
|
|
|
|
});
|
2026-02-04 10:30:28 +08:00
|
|
|
|
|
|
|
|
res.writeHead(200, {
|
|
|
|
|
'Content-Length': contentLength,
|
|
|
|
|
'Content-Type': contentType,
|
|
|
|
|
'Accept-Ranges': 'bytes',
|
2026-06-07 00:02:14 +08:00
|
|
|
'X-Proxy-Cache': 'MISS',
|
2026-02-04 10:30:28 +08:00
|
|
|
});
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
try {
|
|
|
|
|
for await (const chunk of upstream) {
|
|
|
|
|
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
|
|
|
|
|
task.currentSize += buffer.length;
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (cacheWritable) {
|
|
|
|
|
try {
|
|
|
|
|
await writeChunk(fileStream, buffer);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
cacheWritable = false;
|
|
|
|
|
fileStream.destroy();
|
|
|
|
|
removeFileIfExists(tempPath);
|
|
|
|
|
console.warn('[Proxy] Cache write failed; continuing response without cache:', err);
|
|
|
|
|
}
|
2026-02-06 17:01:45 +08:00
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-02-05 18:52:58 +08:00
|
|
|
if (clientConnected && !res.writableEnded) {
|
2026-06-07 00:02:14 +08:00
|
|
|
await writeChunk(res, buffer);
|
2026-02-05 18:52:58 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
}
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (cacheWritable) {
|
|
|
|
|
await endWritable(fileStream);
|
|
|
|
|
finalizeCacheFile(task);
|
|
|
|
|
}
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (clientConnected && !res.writableEnded) {
|
|
|
|
|
res.end();
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
fileStream.destroy();
|
|
|
|
|
removeFileIfExists(tempPath);
|
|
|
|
|
if (!res.headersSent) {
|
|
|
|
|
sendError(res, err instanceof ProxyHttpError ? err.statusCode : 502, 'Proxy stream error');
|
|
|
|
|
} else if (!res.writableEnded) {
|
|
|
|
|
res.destroy();
|
|
|
|
|
}
|
|
|
|
|
throw err;
|
|
|
|
|
} finally {
|
|
|
|
|
if (downloadTasks.get(cacheFilePath) === task) {
|
|
|
|
|
downloadTasks.delete(cacheFilePath);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
async function handleMusicRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
|
|
|
|
|
const parsedUrl = new URL(req.url || '', `http://127.0.0.1:${PORT}`);
|
|
|
|
|
const id = parsedUrl.searchParams.get('id');
|
|
|
|
|
const source = parsedUrl.searchParams.get('source');
|
|
|
|
|
const quality = parsedUrl.searchParams.get('quality') || 'standard';
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (!id || !source) {
|
|
|
|
|
sendError(res, 400, 'Missing id or source');
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const cacheKey = `${source}:${id}:${quality}`;
|
|
|
|
|
const cacheFilePath = getCachePath(source, id, quality);
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (isValidCacheFile(cacheFilePath)) {
|
|
|
|
|
if (serveFromCache(req, res, cacheFilePath)) return;
|
|
|
|
|
console.warn('[Proxy] Cache metadata/file mismatch; removing stale cache');
|
|
|
|
|
removeCacheFiles(cacheFilePath);
|
|
|
|
|
}
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
let playUrl = await resolvePlayUrl(source, id, quality);
|
|
|
|
|
if (!playUrl) {
|
|
|
|
|
sendError(res, 502, 'Failed to obtain playback URL');
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-02-05 18:52:58 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const maxAttempts = 2;
|
|
|
|
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
|
|
|
try {
|
|
|
|
|
const activeTask = downloadTasks.get(cacheFilePath);
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (req.method === 'HEAD') {
|
|
|
|
|
await proxyDirect(req, res, playUrl);
|
|
|
|
|
} else if (activeTask) {
|
|
|
|
|
if (!serveFromPartialCache(req, res, activeTask)) {
|
|
|
|
|
await proxyDirect(req, res, playUrl, activeTask.contentType);
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
} else if (isSeekRange(req.headers.range)) {
|
|
|
|
|
startBackgroundDownload(playUrl, cacheFilePath);
|
|
|
|
|
await proxyDirect(req, res, playUrl);
|
|
|
|
|
} else {
|
|
|
|
|
await streamAndCache(req, res, playUrl, cacheFilePath);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
} catch (err: any) {
|
|
|
|
|
if (res.headersSent || res.writableEnded || res.destroyed) {
|
|
|
|
|
console.warn('[Proxy] Request failed after response started:', err);
|
|
|
|
|
return;
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
console.warn(`[Proxy] Request failed (${attempt}/${maxAttempts}) for ${cacheKey}:`, err);
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (attempt < maxAttempts) {
|
|
|
|
|
playUrl = await resolvePlayUrl(source, id, quality, true);
|
|
|
|
|
if (playUrl) continue;
|
|
|
|
|
}
|
2026-02-04 10:30:28 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
const statusCode = err instanceof ProxyHttpError ? err.statusCode : 502;
|
|
|
|
|
sendError(res, statusCode, 'Proxy Error');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-02-04 11:16:46 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
export function getCacheDir(): string {
|
2026-02-04 14:14:40 +08:00
|
|
|
return ensureCacheDir();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function getCacheSize(): string {
|
|
|
|
|
const dir = ensureCacheDir();
|
|
|
|
|
if (!fs.existsSync(dir)) return '0 B';
|
|
|
|
|
|
|
|
|
|
let totalSize = 0;
|
|
|
|
|
try {
|
2026-06-07 00:02:14 +08:00
|
|
|
for (const file of fs.readdirSync(dir)) {
|
2026-02-04 14:14:40 +08:00
|
|
|
const filePath = path.join(dir, file);
|
2026-06-07 00:02:14 +08:00
|
|
|
const stat = fs.statSync(filePath);
|
|
|
|
|
if (stat.isFile()) totalSize += stat.size;
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error('[Proxy] Failed to calculate cache size:', err);
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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`;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
export function isPersistCacheEnabled(): boolean {
|
2026-02-04 14:14:40 +08:00
|
|
|
return persistCacheEnabled;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
export function setPersistCache(persist: boolean): void {
|
2026-02-04 14:14:40 +08:00
|
|
|
persistCacheEnabled = persist;
|
|
|
|
|
console.log(`[Proxy] Cache persistence set to: ${persist}`);
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function abortAllDownloads(): void {
|
|
|
|
|
for (const [, task] of downloadTasks) {
|
|
|
|
|
task.abortController.abort();
|
|
|
|
|
}
|
|
|
|
|
downloadTasks.clear();
|
|
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
export function clearCacheNow(): void {
|
|
|
|
|
const dir = ensureCacheDir();
|
|
|
|
|
abortAllDownloads();
|
|
|
|
|
urlCache.clear();
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
try {
|
|
|
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
|
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
|
|
|
console.log('[Proxy] Cache cleared');
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('[Proxy] Failed to clear cache:', err);
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
export function cleanupCache(): void {
|
|
|
|
|
abortAllDownloads();
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (!persistCacheEnabled && CACHE_DIR && fs.existsSync(CACHE_DIR)) {
|
2026-02-04 11:16:46 +08:00
|
|
|
try {
|
|
|
|
|
fs.rmSync(CACHE_DIR, { recursive: true, force: true });
|
|
|
|
|
console.log('[Proxy] Cache cleanup complete');
|
2026-06-07 00:02:14 +08:00
|
|
|
} catch (err) {
|
|
|
|
|
console.error('[Proxy] Failed to cleanup cache:', err);
|
2026-02-04 11:16:46 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
function cleanupTempFiles(): void {
|
2026-02-04 14:14:40 +08:00
|
|
|
const dir = ensureCacheDir();
|
2026-06-07 00:02:14 +08:00
|
|
|
const now = Date.now();
|
|
|
|
|
|
2026-02-04 14:14:40 +08:00
|
|
|
try {
|
2026-06-07 00:02:14 +08:00
|
|
|
for (const file of fs.readdirSync(dir)) {
|
|
|
|
|
if (!file.endsWith('.tmp')) continue;
|
|
|
|
|
|
|
|
|
|
const tempPath = path.join(dir, file);
|
|
|
|
|
const cachePath = tempPath.slice(0, -4);
|
|
|
|
|
if (downloadTasks.has(cachePath)) continue;
|
|
|
|
|
|
|
|
|
|
const stat = fs.statSync(tempPath);
|
|
|
|
|
if (now - stat.mtimeMs > STALE_TEMP_TTL_MS) {
|
|
|
|
|
removeFileIfExists(tempPath);
|
|
|
|
|
console.log(`[Proxy] Removed stale temp cache: ${file}`);
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
|
|
|
|
}
|
2026-06-07 00:02:14 +08:00
|
|
|
} catch (err) {
|
|
|
|
|
console.warn('[Proxy] Failed to cleanup temp cache files:', err);
|
2026-02-04 14:14:40 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
export function startProxyServer(persistCache = true): http.Server {
|
2026-02-04 11:16:46 +08:00
|
|
|
persistCacheEnabled = persistCache;
|
2026-06-07 00:02:14 +08:00
|
|
|
ensureCacheDir();
|
|
|
|
|
cleanupTempFiles();
|
2026-02-04 11:16:46 +08:00
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (serverInstance) {
|
|
|
|
|
return serverInstance;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!cleanupTimer) {
|
|
|
|
|
cleanupTimer = setInterval(cleanupTempFiles, 30 * 60 * 1000);
|
|
|
|
|
cleanupTimer.unref?.();
|
|
|
|
|
}
|
2026-02-04 14:14:40 +08:00
|
|
|
|
2026-02-04 10:30:28 +08:00
|
|
|
const server = http.createServer(async (req, res) => {
|
2026-06-07 00:02:14 +08:00
|
|
|
setCommonHeaders(res);
|
2026-02-04 10:30:28 +08:00
|
|
|
|
|
|
|
|
if (req.method === 'OPTIONS') {
|
2026-06-07 00:02:14 +08:00
|
|
|
res.writeHead(204);
|
2026-02-04 10:30:28 +08:00
|
|
|
res.end();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
|
|
|
sendError(res, 405, 'Method Not Allowed');
|
2026-02-04 10:30:28 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
2026-06-07 00:02:14 +08:00
|
|
|
const parsedUrl = new URL(req.url || '', `http://127.0.0.1:${PORT}`);
|
2026-02-04 10:30:28 +08:00
|
|
|
if (parsedUrl.pathname !== '/music') {
|
2026-06-07 00:02:14 +08:00
|
|
|
sendError(res, 404, 'Not Found');
|
2026-02-04 10:30:28 +08:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
await handleMusicRequest(req, res);
|
2026-02-04 10:30:28 +08:00
|
|
|
} catch (err) {
|
2026-06-07 00:02:14 +08:00
|
|
|
console.error('[Proxy] Internal error:', err);
|
|
|
|
|
sendError(res, 500, 'Internal Server Error');
|
2026-02-04 10:30:28 +08:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
server.on('clientError', (err, socket) => {
|
|
|
|
|
console.warn('[Proxy] Client socket error:', err.message);
|
|
|
|
|
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
server.on('error', (err) => {
|
|
|
|
|
console.error('[Proxy] Server error:', err);
|
|
|
|
|
});
|
|
|
|
|
|
2026-02-04 10:30:28 +08:00
|
|
|
server.listen(PORT, '127.0.0.1', () => {
|
|
|
|
|
console.log(`[Proxy] Server running at http://127.0.0.1:${PORT}/music`);
|
|
|
|
|
console.log(`[Proxy] Cache dir: ${CACHE_DIR}`);
|
2026-06-07 00:02:14 +08:00
|
|
|
console.log(`[Proxy] Persist cache: ${persistCacheEnabled}`);
|
2026-02-04 10:30:28 +08:00
|
|
|
});
|
|
|
|
|
|
2026-06-07 00:02:14 +08:00
|
|
|
serverInstance = server;
|
2026-02-04 10:30:28 +08:00
|
|
|
return server;
|
|
|
|
|
}
|