-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdev-server.js
More file actions
208 lines (177 loc) · 6.12 KB
/
dev-server.js
File metadata and controls
208 lines (177 loc) · 6.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { existsSync, readFileSync } from 'fs';
import { createTelegramBotService } from './telegram/bot.js';
// ES模块中获取__dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function loadEnvFile() {
const envPath = path.join(__dirname, '.env');
if (!existsSync(envPath)) {
return;
}
const envContent = readFileSync(envPath, 'utf-8');
for (const rawLine of envContent.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) {
continue;
}
const separatorIndex = line.indexOf('=');
if (separatorIndex === -1) {
continue;
}
const key = line.slice(0, separatorIndex).trim();
let value = line.slice(separatorIndex + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
if (key && process.env[key] === undefined) {
process.env[key] = value;
}
}
}
loadEnvFile();
const app = express();
const PORT = process.env.PORT || 3000;
const telegramBotService = createTelegramBotService();
let isShuttingDown = false;
// 中间件配置
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// CORS配置 - 仅在开发环境使用,生产环境由API路由自己处理
if (process.env.NODE_ENV !== 'production') {
app.use((req, res, next) => {
// 开发环境的CORS配置
const allowedOrigins = [
'http://localhost:3000',
'http://127.0.0.1:3000',
'http://localhost:8080', // 可能的其他开发端口
'http://127.0.0.1:8080'
];
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.header('Access-Control-Allow-Origin', origin);
} else {
// 开发环境默认允许localhost
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
}
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Credentials', 'false');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
console.log('🔧 开发环境CORS中间件已启用');
} else {
console.log('🔒 生产环境:CORS由API路由自行处理');
}
// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
// 动态导入API路由处理器
async function loadApiHandler(modulePath) {
try {
const module = await import(modulePath);
return module.default;
} catch (error) {
console.error(`加载API模块失败: ${modulePath}`, error);
return null;
}
}
// API路由 - 二维码生成
app.post('/api/qrcode', async (req, res) => {
try {
const handler = await loadApiHandler('./api/qrcode.js');
if (handler) {
await handler(req, res);
} else {
res.status(500).json({ success: false, message: '无法加载二维码API' });
}
} catch (error) {
console.error('二维码API错误:', error);
res.status(500).json({ success: false, message: '服务器内部错误' });
}
});
// API路由 - 状态检查
app.post('/api/check-status', async (req, res) => {
try {
const handler = await loadApiHandler('./api/check-status.js');
if (handler) {
await handler(req, res);
} else {
res.status(500).json({ success: false, message: '无法加载状态检查API' });
}
} catch (error) {
console.error('状态检查API错误:', error);
res.status(500).json({ success: false, message: '服务器内部错误' });
}
});
// 处理所有其他路由,返回index.html(SPA支持)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// 错误处理中间件
app.use((error, req, res, next) => {
console.error('服务器错误:', error);
res.status(500).json({
success: false,
message: '服务器内部错误',
error: process.env.NODE_ENV === 'development' ? error.message : undefined
});
});
// 启动服务器
const server = app.listen(PORT, async () => {
console.log(`🚀 Cookie Butler 开发服务器启动成功!`);
console.log(`📱 访问地址: http://localhost:${PORT}`);
console.log(`🔧 环境: ${process.env.NODE_ENV || 'development'}`);
console.log(`⏰ 启动时间: ${new Date().toLocaleString()}`);
console.log('');
console.log('💡 提示:');
console.log(' - 修改代码后需要重启服务器');
console.log(' - 推荐使用 "vercel dev" 获得热重载和完整功能');
console.log(' - 按 Ctrl+C 停止服务器');
if (telegramBotService.isEnabled()) {
try {
await telegramBotService.start();
} catch (error) {
console.error('[Telegram] 启动失败:', error.message);
}
} else {
console.log('[Telegram] 未配置 TELEGRAM_BOT_TOKEN,跳过机器人启动');
}
});
async function shutdown(signal) {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
console.log(`\n🛑 收到 ${signal},正在关闭服务...`);
try {
await telegramBotService.stop();
} catch (error) {
console.error('[Telegram] 停止失败:', error.message);
}
server.close((error) => {
if (error) {
console.error('服务器关闭失败:', error);
process.exit(1);
}
process.exit(0);
});
setTimeout(() => {
console.error('服务器关闭超时,强制退出');
process.exit(1);
}, 5000).unref();
}
process.on('SIGINT', () => {
shutdown('SIGINT');
});
process.on('SIGTERM', () => {
shutdown('SIGTERM');
});