Spaces:
Paused
Paused
| import dotenv from 'dotenv'; | |
| import chalk from 'chalk'; | |
| import { fileURLToPath } from 'url'; | |
| import { dirname, join } from 'path'; | |
| const __filename = fileURLToPath(import.meta.url); | |
| const __dirname = dirname(__filename); | |
| dotenv.config({ path: join(dirname(__dirname), '.env') }); | |
| const logger = { | |
| info: (message) => console.log(chalk.blue(`[ProxyServer] ${message}`)), | |
| error: (message) => console.error(chalk.red(`[ProxyServer] ${message}`)), | |
| warning: (message) => console.warn(chalk.yellow(`[ProxyServer] ${message}`)), | |
| success: (message) => console.log(chalk.green(`[ProxyServer] ${message}`)), | |
| }; | |
| /** | |
| * 简化的代理服务器管理类 | |
| */ | |
| class ProxyServer { | |
| constructor() { | |
| this.enabled = process.env.ENABLE_PROXY_SERVER === 'true'; | |
| this.proxyUrl = process.env.HTTP_PROXY || process.env.HTTPS_PROXY || ''; | |
| this.isConnected = false; | |
| } | |
| /** | |
| * 启动代理服务器 | |
| */ | |
| async start() { | |
| if (!this.enabled) { | |
| logger.info('代理服务器未启用,跳过启动'); | |
| return false; | |
| } | |
| if (!this.proxyUrl) { | |
| logger.warning('未设置代理URL (HTTP_PROXY),跳过代理验证'); | |
| return false; | |
| } | |
| logger.info('正在验证代理连接...'); | |
| try { | |
| const isValid = await this.validateProxyConnection(); | |
| if (isValid) { | |
| this.isConnected = true; | |
| logger.success('代理服务连接成功'); | |
| return true; | |
| } else { | |
| logger.error('代理服务连接失败'); | |
| return false; | |
| } | |
| } catch (error) { | |
| logger.error(`连接代理服务时出错: ${error.message}`); | |
| return false; | |
| } | |
| } | |
| /** | |
| * 验证代理连接 | |
| */ | |
| async validateProxyConnection() { | |
| try { | |
| // 修复导入方式 | |
| const HttpProxyAgent = (await import('http-proxy-agent')).default; | |
| const fetch = (await import('node-fetch')).default; | |
| const agent = new HttpProxyAgent(this.proxyUrl); | |
| const response = await fetch('https://httpbin.org/ip', { | |
| agent, | |
| timeout: 10000 | |
| }); | |
| if (response.ok) { | |
| const data = await response.json(); | |
| logger.info(`代理连接测试成功,出口IP: ${data.origin}`); | |
| return true; | |
| } else { | |
| logger.error(`代理连接测试失败,状态码: ${response.status}`); | |
| return false; | |
| } | |
| } catch (error) { | |
| logger.error(`代理连接验证失败: ${error.message}`); | |
| return false; | |
| } | |
| } | |
| /** | |
| * 停止代理服务器 | |
| */ | |
| stop() { | |
| this.isConnected = false; | |
| logger.success('代理服务已断开'); | |
| } | |
| /** | |
| * 获取代理状态 | |
| */ | |
| getStatus() { | |
| return { | |
| enabled: this.enabled, | |
| connected: this.isConnected, | |
| proxyConfigured: !!this.proxyUrl | |
| }; | |
| } | |
| } | |
| const proxyServer = new ProxyServer(); | |
| export { proxyServer }; | |