alist-proxy/source.js

586 lines
25 KiB
JavaScript
Raw Normal View History

2024-10-15 18:54:26 +08:00
const http = require('http');
const https = require('https');
const url = require('url');
const querystring = require('querystring');
const fs = require('fs');
const pathModule = require('path');
const crypto = require('crypto');
2025-05-26 08:32:48 +08:00
const path = require('path');
const sharp = require('sharp');
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
const CACHE_DIR_NAME = '.cache';
const DEFAULT_PORT = 9001;
const DEFAULT_API_ENDPOINT = 'http://183.6.121.121:9005/get/';
const cacheDir = pathModule.join(__dirname, CACHE_DIR_NAME);
2024-10-15 18:54:26 +08:00
const pathIndex = {};
2025-05-26 08:32:48 +08:00
// 访问计数器
2024-10-15 18:54:26 +08:00
const viewsInfo = {
request: 0,
cacheHit: 0,
apiCall: 0,
cacheCall: 0,
2024-11-06 21:16:35 +08:00
cacheReadError: 0,
fetchApiError: 0,
2024-11-07 13:14:41 +08:00
fetchApiWarning: 0,
2025-05-26 08:32:48 +08:00
increment: function(key) {
if (this.hasOwnProperty(key)) {
this[key]++;
}
}
2024-10-15 18:54:26 +08:00
};
2025-05-26 08:32:48 +08:00
let port = DEFAULT_PORT;
let apiEndpoint = DEFAULT_API_ENDPOINT;
// 解析命令行参数函数
function parseArguments() {
const args = process.argv.slice(2);
args.forEach(arg => {
const cleanArg = arg.startsWith('--') ? arg.substring(2) : arg;
const [key, value] = cleanArg.split('=');
if (key === 'port' && value) {
const parsedPort = parseInt(value, 10);
if (!isNaN(parsedPort)) {
port = parsedPort;
}
} else if (key === 'api' && value) {
apiEndpoint = value;
}
});
}
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
// 初始化函数,包含参数解析和目录创建
function initializeApp() {
parseArguments();
if (!fs.existsSync(cacheDir)) {
try {
fs.mkdirSync(cacheDir, { recursive: true });
console.log(`Cache directory created: ${cacheDir}`);
} catch (err) {
console.error(`Error creating cache directory ${cacheDir}:`, err);
process.exit(1); // Exit if cache directory cannot be created
}
2024-10-15 18:54:26 +08:00
}
}
2025-05-26 08:32:48 +08:00
initializeApp();
const CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000; // 24 hours
const CACHE_CLEANUP_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
const HTTP_STATUS = {
OK: 200,
NO_CONTENT: 204,
REDIRECT: 302,
NOT_MODIFIED: 304,
BAD_REQUEST: 400,
NOT_FOUND: 404,
INTERNAL_SERVER_ERROR: 500,
BAD_GATEWAY: 502,
};
2024-10-15 18:54:26 +08:00
// 定时清理过期缓存数据
setInterval(() => {
const currentTime = Date.now();
for (const key in pathIndex) {
2025-05-26 08:32:48 +08:00
if (currentTime - pathIndex[key].timestamp > CACHE_EXPIRY_MS) {
2024-10-15 18:54:26 +08:00
delete pathIndex[key];
2025-05-26 08:32:48 +08:00
// Consider deleting actual cache files as well if not managed elsewhere
2024-10-15 18:54:26 +08:00
}
}
2025-05-26 08:32:48 +08:00
}, CACHE_CLEANUP_INTERVAL_MS);
// 统一发送错误响应
function sendErrorResponse(res, statusCode, message) {
if (!res.headersSent) {
res.writeHead(statusCode, { 'Content-Type': 'text/plain;charset=UTF-8' });
res.end(message);
}
}
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
// --- Request Handling Logic ---
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
async function handleFavicon(req, res) {
res.writeHead(HTTP_STATUS.NO_CONTENT);
res.end();
}
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
async function handleEndpoint(req, res, parsedUrl) {
if (parsedUrl.query.api) {
const urlRegex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w.-]*)*\/?$/;
if (urlRegex.test(parsedUrl.query.api)) {
apiEndpoint = parsedUrl.query.api;
console.log(`API endpoint updated to: ${apiEndpoint}`);
}
}
res.writeHead(HTTP_STATUS.OK, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
code: HTTP_STATUS.OK,
data: {
api: apiEndpoint,
port: port,
cacheDir: cacheDir,
pathIndexCount: Object.keys(pathIndex).length,
viewsInfo: {
request: viewsInfo.request,
cacheHit: viewsInfo.cacheHit,
apiCall: viewsInfo.apiCall,
cacheCall: viewsInfo.cacheCall,
cacheReadError: viewsInfo.cacheReadError,
fetchApiError: viewsInfo.fetchApiError,
fetchApiWarning: viewsInfo.fetchApiWarning,
}
}
}));
}
async function handleApiRedirect(res, apiData) {
res.writeHead(HTTP_STATUS.REDIRECT, { Location: apiData.data.url });
res.end();
}
2024-11-03 14:28:33 +08:00
2025-05-26 08:32:48 +08:00
async function processSuccessfulApiData(apiData, uniqidhex, reqPath, token, sign, res) {
const { url: realUrl, cloudtype, expiration, path: apiPath, headers, uniqid } = apiData.data;
const data = { realUrl, cloudtype, expiration: expiration * 1000, path: apiPath, headers, uniqid };
2024-11-03 00:12:15 +08:00
2025-05-26 08:32:48 +08:00
pathIndex[uniqidhex] = { uniqid: data.uniqid, timestamp: Date.now() };
const cacheMetaFile = pathModule.join(cacheDir, `${data.uniqid}.meta`);
const cacheContentFile = pathModule.join(cacheDir, `${data.uniqid}.content`);
const tempCacheContentFile = pathModule.join(cacheDir, `${data.uniqid}_${crypto.randomBytes(16).toString('hex')}.temp`);
2024-11-02 14:43:49 +08:00
2025-05-26 08:32:48 +08:00
try {
fs.writeFileSync(cacheMetaFile, JSON.stringify(data));
} catch (writeError) {
console.error(`Error writing meta file ${cacheMetaFile}:`, writeError);
sendErrorResponse(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Failed to write cache metadata.');
2024-10-15 18:54:26 +08:00
return;
}
2025-05-26 08:32:48 +08:00
if (fs.existsSync(cacheContentFile)) {
const stats = fs.statSync(cacheContentFile);
const contentLength = stats.size;
// If file is very small and content length from API differs, consider re-fetching.
// The 2048 threshold seems arbitrary; could be configurable or based on content type.
if (contentLength < 2048 && data.headers['content-length'] && parseInt(data.headers['content-length'], 10) !== contentLength) {
console.warn(`Content length mismatch for ${cacheContentFile}. API: ${data.headers['content-length']}, Cache: ${contentLength}. Re-fetching.`);
fetchAndServe(data, tempCacheContentFile, cacheContentFile, cacheMetaFile, res);
} else {
serveFromCache(data, cacheContentFile, cacheMetaFile, res);
2024-11-07 17:15:39 +08:00
}
2025-05-26 08:32:48 +08:00
} else {
fetchAndServe(data, tempCacheContentFile, cacheContentFile, cacheMetaFile, res);
2024-10-15 18:54:26 +08:00
}
2025-05-26 08:32:48 +08:00
}
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
async function tryServeFromStaleCacheOrError(uniqidhex, res, errorMessage) {
if (pathIndex[uniqidhex]) {
const cacheMetaFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex].uniqid}.meta`);
const cacheContentFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex].uniqid}.content`);
if (fs.existsSync(cacheMetaFile) && fs.existsSync(cacheContentFile)) {
console.warn(`API call failed or returned non-200. Serving stale cache for ${uniqidhex}`);
try {
const cacheData = JSON.parse(fs.readFileSync(cacheMetaFile, 'utf8'));
serveFromCache(cacheData, cacheContentFile, cacheMetaFile, res);
return;
} catch (parseError) {
console.error(`Error parsing stale meta file ${cacheMetaFile}:`, parseError);
// Fall through to generic error if stale cache is also broken
}
}
2024-11-02 14:43:49 +08:00
}
2025-05-26 08:32:48 +08:00
sendErrorResponse(res, HTTP_STATUS.BAD_GATEWAY, errorMessage || 'Bad Gateway');
}
2024-11-02 14:43:49 +08:00
2025-05-26 08:32:48 +08:00
async function handleMainRequest(req, res) {
req.url = req.url.replace(/\/{2,}/g, '/');
const parsedUrl = url.parse(req.url, true);
const sign = parsedUrl.query.sign || '';
let reqPath = parsedUrl.pathname.split('/')[1] || ''; // Ensure reqPath is not undefined
let token = parsedUrl.pathname.split('/').slice(2).join('/');
2024-11-02 14:43:49 +08:00
2025-05-26 08:32:48 +08:00
if (reqPath === 'favicon.ico') return handleFavicon(req, res);
if (reqPath === 'endpoint') return handleEndpoint(req, res, parsedUrl);
if (!token && reqPath) { // If token is empty but reqPath is not, assume reqPath is the token
token = reqPath;
reqPath = 'app'; // Default to 'app' if only one path segment is provided
2024-10-15 18:54:26 +08:00
}
2025-05-26 08:32:48 +08:00
const ALLOWED_PATHS = ['avatar', 'go', 'bbs', 'www', 'url', 'thumb', 'app'];
if (!ALLOWED_PATHS.includes(reqPath) || !token) {
return sendErrorResponse(res, HTTP_STATUS.BAD_REQUEST, `Bad Request: Invalid path or missing token.`);
}
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
viewsInfo.increment('request');
2024-11-05 11:24:16 +08:00
const uniqidhex = crypto.createHash('md5').update(reqPath + token + sign).digest('hex');
2024-10-15 18:54:26 +08:00
let cacheMetaFile = '';
let cacheContentFile = '';
if (pathIndex[uniqidhex]) {
cacheMetaFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex].uniqid}.meta`);
cacheContentFile = pathModule.join(cacheDir, `${pathIndex[uniqidhex].uniqid}.content`);
}
if (pathIndex[uniqidhex] && isCacheValid(cacheMetaFile, cacheContentFile)) {
2024-11-02 14:43:49 +08:00
const { cacheData, isNotModified } = await checkCacheHeaders(req, cacheMetaFile);
if (isNotModified) {
2025-05-26 08:32:48 +08:00
res.writeHead(HTTP_STATUS.NOT_MODIFIED);
2024-11-02 14:43:49 +08:00
res.end();
} else {
2025-05-26 08:32:48 +08:00
viewsInfo.increment('cacheHit');
2024-11-02 15:47:27 +08:00
serveFromCache(cacheData, cacheContentFile, cacheMetaFile, res);
2024-11-02 14:43:49 +08:00
}
2024-10-15 18:54:26 +08:00
} else {
try {
2025-05-26 08:32:48 +08:00
viewsInfo.increment('apiCall');
2024-11-03 14:28:33 +08:00
const apiData = await fetchApiData(reqPath, token, sign);
2024-11-07 13:14:41 +08:00
2025-05-26 08:32:48 +08:00
if (apiData.code === HTTP_STATUS.REDIRECT || apiData.code === 301) {
return handleApiRedirect(res, apiData);
2024-11-07 13:14:41 +08:00
}
2025-05-26 08:32:48 +08:00
if (apiData.code === HTTP_STATUS.OK && apiData.data && apiData.data.url) {
await processSuccessfulApiData(apiData, uniqidhex, reqPath, token, sign, res);
2024-10-15 18:54:26 +08:00
} else {
2025-05-26 08:32:48 +08:00
viewsInfo.increment('fetchApiWarning');
await tryServeFromStaleCacheOrError(uniqidhex, res, apiData.message);
2024-10-15 18:54:26 +08:00
}
} catch (error) {
2025-05-26 08:32:48 +08:00
viewsInfo.increment('fetchApiError');
console.error('Error in API call or processing:', error);
await tryServeFromStaleCacheOrError(uniqidhex, res, `Bad Gateway: API request failed. ${error.message}`);
2024-10-15 18:54:26 +08:00
}
}
2025-05-26 08:32:48 +08:00
}
const server = http.createServer(handleMainRequest);
2024-10-15 18:54:26 +08:00
2024-11-02 14:43:49 +08:00
// 检查缓存头并返回是否为304
2025-05-26 08:32:48 +08:00
async function checkCacheHeaders(req, cacheMetaFile) {
try {
const metaContent = fs.readFileSync(cacheMetaFile, 'utf8');
const cacheData = JSON.parse(metaContent);
const ifNoneMatch = req.headers['if-none-match'];
const ifModifiedSince = req.headers['if-modified-since'];
// Check ETag first
if (ifNoneMatch && cacheData.uniqid && ifNoneMatch === cacheData.uniqid) {
return { cacheData, isNotModified: true };
2024-11-02 14:43:49 +08:00
}
2025-05-26 08:32:48 +08:00
// Check If-Modified-Since
if (ifModifiedSince && cacheData.headers && cacheData.headers['last-modified']) {
try {
const lastModifiedDate = new Date(cacheData.headers['last-modified']);
const ifModifiedSinceDate = new Date(ifModifiedSince);
// The time resolution of an HTTP date is one second.
// If If-Modified-Since is at least as new as Last-Modified, send 304.
if (lastModifiedDate.getTime() <= ifModifiedSinceDate.getTime()) {
return { cacheData, isNotModified: true };
}
} catch (dateParseError) {
console.warn(`Error parsing date for cache header check (${cacheMetaFile}):`, dateParseError);
// Proceed as if not modified check failed if dates are invalid
}
}
return { cacheData, isNotModified: false };
} catch (error) {
console.error(`Error reading or parsing cache meta file ${cacheMetaFile} in checkCacheHeaders:`, error);
// If we can't read meta, assume cache is invalid or treat as not modified: false
// Returning a dummy cacheData or null might be better depending on how caller handles it.
// For now, let it propagate and potentially fail later if cacheData is expected.
// Or, more safely, indicate cache is not valid / not modified is false.
return { cacheData: null, isNotModified: false }; // Indicate failure to load cacheData
2024-11-02 14:43:49 +08:00
}
2025-05-26 08:32:48 +08:00
}
2024-11-02 14:43:49 +08:00
2024-10-15 18:54:26 +08:00
// 检查缓存是否有效
2025-05-26 08:32:48 +08:00
function isCacheValid(cacheMetaFile, cacheContentFile) {
if (!fs.existsSync(cacheMetaFile) || !fs.existsSync(cacheContentFile)) {
return false;
}
try {
const metaContent = fs.readFileSync(cacheMetaFile, 'utf8');
const cacheData = JSON.parse(metaContent);
// Ensure expiration is a number and in the future
return typeof cacheData.expiration === 'number' && cacheData.expiration > Date.now();
} catch (error) {
console.warn(`Error reading or parsing cache meta file ${cacheMetaFile} for validation:`, error);
return false; // If meta file is corrupt or unreadable, cache is not valid
}
}
2024-10-15 18:54:26 +08:00
// 从 API 获取数据
2025-05-26 08:32:48 +08:00
const API_TIMEOUT_MS = 5000;
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36';
async function fetchApiData(reqPath, token, sign) {
const queryParams = querystring.stringify({
type: reqPath,
sign: sign
});
const apiUrl = `${apiEndpoint}?${queryParams}`;
const parsedApiUrl = new URL(apiUrl);
const protocol = parsedApiUrl.protocol === 'https:' ? https : http;
const options = {
method: 'GET',
headers: {
'Accept': 'application/json; charset=utf-8',
'User-Agent': USER_AGENT,
'token': token
},
timeout: API_TIMEOUT_MS,
rejectUnauthorized: false, // Allow self-signed certificates, use with caution
};
2024-10-15 18:54:26 +08:00
return new Promise((resolve, reject) => {
2025-05-26 08:32:48 +08:00
const apiReq = protocol.request(apiUrl, options, (apiRes) => {
let responseData = '';
apiRes.setEncoding('utf8');
apiRes.on('data', chunk => responseData += chunk);
2024-10-15 18:54:26 +08:00
apiRes.on('end', () => {
try {
2025-05-26 08:32:48 +08:00
if (apiRes.statusCode >= 400) {
// Treat HTTP errors from API as rejections for easier handling
console.error(`API request to ${apiUrl} failed with status ${apiRes.statusCode}: ${responseData}`);
// Attempt to parse for a message, but prioritize status code for error type
let errorPayload = { code: apiRes.statusCode, message: `API Error: ${apiRes.statusCode}` };
try {
const parsedError = JSON.parse(responseData);
if(parsedError && parsedError.message) errorPayload.message = parsedError.message;
} catch (e) { /* Ignore if response is not JSON */ }
resolve(errorPayload); // Resolve with error structure for consistency
return;
}
resolve(JSON.parse(responseData));
} catch (parseError) {
console.error(`Error parsing JSON response from ${apiUrl}:`, parseError, responseData);
reject(new Error(`Failed to parse API response: ${parseError.message}`));
2024-10-15 18:54:26 +08:00
}
});
});
2025-05-26 08:32:48 +08:00
apiReq.on('timeout', () => {
apiReq.destroy(); // Destroy the request to free up resources
console.error(`API request to ${apiUrl} timed out after ${API_TIMEOUT_MS}ms`);
reject(new Error('API request timed out'));
});
apiReq.on('error', (networkError) => {
console.error(`API request to ${apiUrl} failed:`, networkError);
reject(networkError);
});
2024-10-15 18:54:26 +08:00
apiReq.end();
});
2025-05-26 08:32:48 +08:00
}
2024-10-15 18:54:26 +08:00
// 从真实 URL 获取数据并写入缓存
2025-05-26 08:32:48 +08:00
const REAL_URL_FETCH_TIMEOUT_MS = 0; // 0 means no timeout for the actual file download
2024-11-02 15:47:27 +08:00
const fetchAndServe = (data, tempCacheContentFile, cacheContentFile, cacheMetaFile, res) => {
2025-05-26 08:32:48 +08:00
const protocol = data.realUrl.startsWith('https:') ? https : http;
2025-05-26 08:32:48 +08:00
protocol.get(data.realUrl, { timeout: REAL_URL_FETCH_TIMEOUT_MS, rejectUnauthorized: false }, (realRes) => {
2024-10-15 18:54:26 +08:00
const cacheStream = fs.createWriteStream(tempCacheContentFile, { flags: 'w' });
let isVideo = data.path && typeof data.path === 'string' && data.path.includes('.mp4');
// 确保 content-length 是有效的
const contentLength = realRes.headers['content-length'];
if (contentLength) {
// contentLength 小于 2KB 且与缓存文件大小不一致时,重新获取
if (contentLength < 2048 && data.headers['content-length'] !== contentLength) {
console.warn('Warning: content-length is different for the response from:', data.realUrl);
2025-05-26 08:32:48 +08:00
sendErrorResponse(res, HTTP_STATUS.BAD_GATEWAY, `Bad Gateway: Content-Length mismatch for ${data.realUrl}`);
// Clean up temp file if stream hasn't started or failed early
if (fs.existsSync(tempCacheContentFile)) {
fs.unlinkSync(tempCacheContentFile);
}
return;
}
2024-10-15 18:54:26 +08:00
data.headers['content-length'] = contentLength;
2024-11-02 15:47:27 +08:00
// 更新 data 到缓存 cacheMetaFile
fs.writeFileSync(cacheMetaFile, JSON.stringify(data));
2024-10-15 18:54:26 +08:00
} else {
console.warn('Warning: content-length is undefined for the response from:', data.realUrl);
}
2025-05-26 08:32:48 +08:00
const baseHeaders = {
2024-10-15 18:54:26 +08:00
'Cloud-Type': data.cloudtype,
'Cloud-Expiration': data.expiration,
'ETag': data.uniqid || '',
2025-05-26 08:32:48 +08:00
'Cache-Control': 'public, max-age=31536000', // 1 year
2024-10-15 18:54:26 +08:00
'Expires': new Date(Date.now() + 31536000000).toUTCString(),
'Accept-Ranges': 'bytes',
'Connection': 'keep-alive',
2025-05-26 08:32:48 +08:00
'Date': new Date().toUTCString(), // Should be set by the server, but good for consistency
'Last-Modified': data.headers['last-modified'] || new Date(fs.statSync(cacheMetaFile).mtime).toUTCString(), // Prefer API's Last-Modified if available
};
const responseHeaders = {
...baseHeaders,
'Content-Type': realRes.headers['content-type'] || (isVideo ? 'video/mp4' : 'application/octet-stream'), // Prefer actual content-type
...data.headers, // Allow API to override some headers if necessary
2024-10-15 18:54:26 +08:00
};
2025-05-26 08:32:48 +08:00
res.writeHead(realRes.statusCode, responseHeaders);
2024-10-15 18:54:26 +08:00
realRes.pipe(cacheStream);
realRes.pipe(res);
realRes.on('end', () => {
2025-05-26 08:32:48 +08:00
cacheStream.end(() => { // Ensure stream is fully flushed before renaming
if (fs.existsSync(tempCacheContentFile)) {
try {
// Ensure the target directory exists before renaming
const targetDir = pathModule.dirname(cacheContentFile);
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
}
fs.renameSync(tempCacheContentFile, cacheContentFile);
console.log(`Successfully cached: ${cacheContentFile}`);
} catch (renameError) {
console.error(`Error renaming temp cache file ${tempCacheContentFile} to ${cacheContentFile}:`, renameError);
// If rename fails, try to remove the temp file to avoid clutter
try { fs.unlinkSync(tempCacheContentFile); } catch (e) { /* ignore */ }
}
} else {
// This case might indicate an issue if the stream ended but no temp file was created/found
console.warn(`Temp cache file ${tempCacheContentFile} not found after stream end for ${data.realUrl}`);
2024-10-15 18:54:26 +08:00
}
2025-05-26 08:32:48 +08:00
});
2024-10-15 18:54:26 +08:00
});
2025-05-26 08:32:48 +08:00
realRes.on('error', (streamError) => {
console.error(`Error during response stream from ${data.realUrl}:`, streamError);
cacheStream.end(); // Close the writable stream
handleResponseError(res, tempCacheContentFile, data.realUrl); // tempCacheContentFile might be partially written
2024-10-15 18:54:26 +08:00
});
2025-05-26 08:32:48 +08:00
}).on('error', (requestError) => {
console.error(`Error making GET request to ${data.realUrl}:`, requestError);
// No cacheStream involved here if the request itself fails before response
handleResponseError(res, tempCacheContentFile, data.realUrl); // tempCacheContentFile might not exist or be empty
2024-10-15 18:54:26 +08:00
});
};
// 从缓存中读取数据并返回
2025-05-26 08:32:48 +08:00
function serveFromCache(cacheData, cacheContentFile, cacheMetaFile, res) {
if (!cacheData) { // Added check for null cacheData from checkCacheHeaders failure
console.error(`serveFromCache called with null cacheData for ${cacheContentFile}`);
sendErrorResponse(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Cache metadata unavailable.');
return;
}
viewsInfo.increment('cacheCall');
2024-10-15 18:54:26 +08:00
const readStream = fs.createReadStream(cacheContentFile);
2025-05-26 08:32:48 +08:00
const isVideo = cacheData.path && typeof cacheData.path === 'string' && cacheData.path.includes('.mp4');
2024-11-02 15:47:27 +08:00
2025-05-26 08:32:48 +08:00
let currentContentLength = cacheData.headers && cacheData.headers['content-length'] ? parseInt(cacheData.headers['content-length'], 10) : 0;
2024-11-02 15:47:27 +08:00
2025-05-26 08:32:48 +08:00
if (!currentContentLength || currentContentLength === 0) {
try {
const stats = fs.statSync(cacheContentFile);
currentContentLength = stats.size;
if (currentContentLength > 0) {
if (!cacheData.headers) cacheData.headers = {};
cacheData.headers['content-length'] = currentContentLength.toString();
// Update meta file if content-length was missing or zero
fs.writeFileSync(cacheMetaFile, JSON.stringify(cacheData));
console.log(`Updated content-length in ${cacheMetaFile} to ${currentContentLength}`);
} else {
console.warn(`Cached content file ${cacheContentFile} has size 0 or stat failed.`);
// Potentially treat as an error or serve as is if 0 length is valid for some files
}
} catch (statError) {
console.error(`Error stating cache content file ${cacheContentFile}:`, statError);
handleCacheReadError(res, cacheContentFile); // Treat stat error as read error
return;
2024-11-02 15:47:27 +08:00
}
2024-10-15 18:54:26 +08:00
}
readStream.on('open', () => {
2025-05-26 08:32:48 +08:00
const baseHeaders = {
'Cloud-Type': cacheData.cloudtype || 'unknown',
'Cloud-Expiration': cacheData.expiration || 'N/A',
'ETag': cacheData.uniqid || crypto.createHash('md5').update(fs.readFileSync(cacheContentFile)).digest('hex'), // Fallback ETag if missing
'Cache-Control': 'public, max-age=31536000', // 1 year
2024-10-15 18:54:26 +08:00
'Expires': new Date(Date.now() + 31536000000).toUTCString(),
'Accept-Ranges': 'bytes',
'Connection': 'keep-alive',
'Date': new Date().toUTCString(),
2025-05-26 08:32:48 +08:00
'Last-Modified': (cacheData.headers && cacheData.headers['last-modified']) || new Date(fs.statSync(cacheMetaFile).mtime).toUTCString(),
};
const responseHeaders = {
...baseHeaders,
'Content-Type': (cacheData.headers && cacheData.headers['content-type']) || (isVideo ? 'video/mp4' : 'application/octet-stream'),
// Merge other headers from cacheData.headers, letting them override base if necessary
// but ensure our critical headers like Content-Length (if updated) are preserved.
...(cacheData.headers || {}),
'Content-Length': currentContentLength.toString(), // Ensure this is set correctly
};
2024-10-15 18:54:26 +08:00
2025-05-26 08:32:48 +08:00
res.writeHead(HTTP_STATUS.OK, responseHeaders);
2024-10-15 18:54:26 +08:00
readStream.pipe(res);
});
readStream.on('error', (err) => {
2025-05-26 08:32:48 +08:00
console.error(`Read stream error for ${cacheContentFile}:`, err);
handleCacheReadError(res, cacheContentFile);
2024-10-15 18:54:26 +08:00
});
2024-11-06 21:16:35 +08:00
2025-05-26 08:32:48 +08:00
// Handle cases where client closes connection prematurely
res.on('close', () => {
if (!res.writableEnded) {
console.log(`Client closed connection prematurely for ${cacheContentFile}. Destroying read stream.`);
readStream.destroy();
}
});
}
2024-11-06 21:16:35 +08:00
2025-05-26 08:32:48 +08:00
// 处理响应错误
const handleResponseError = (res, tempCacheContentFile, realUrl) => {
viewsInfo.increment('fetchApiError');
console.error(`Error fetching from real URL: ${realUrl}`);
sendErrorResponse(res, HTTP_STATUS.BAD_GATEWAY, `Bad Gateway: Failed to fetch from ${realUrl}`);
2024-10-15 18:54:26 +08:00
if (fs.existsSync(tempCacheContentFile)) {
2025-05-26 08:32:48 +08:00
try {
fs.unlinkSync(tempCacheContentFile);
} catch (unlinkErr) {
console.error(`Error unlinking temp file ${tempCacheContentFile}:`, unlinkErr);
}
2024-10-15 18:54:26 +08:00
}
};
// 处理缓存读取错误
2025-05-26 08:32:48 +08:00
const handleCacheReadError = (res, filePath) => {
viewsInfo.increment('cacheReadError');
console.error(`Error reading cache file: ${filePath}`);
sendErrorResponse(res, HTTP_STATUS.INTERNAL_SERVER_ERROR, 'Internal Server Error: Unable to read cache content file');
2024-10-15 18:54:26 +08:00
};
// 启动服务器
server.listen(port, () => {
console.log(`Proxy server is running on http://localhost:${port}`);
});
// 处理 SIGINT 信号Ctrl+C
process.on('SIGINT', () => {
console.log('Received SIGINT. Shutting down gracefully...');
server.close(() => {
console.log('Server closed.');
process.exit(0);
});
setTimeout(() => {
console.error('Forcing shutdown...');
process.exit(1);
}, 10000);
2025-05-22 15:13:35 +08:00
});