-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
430 lines (385 loc) · 14.2 KB
/
Copy pathserver.js
File metadata and controls
430 lines (385 loc) · 14.2 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import 'dotenv/config';
import { webcrypto } from 'crypto';
if (!globalThis.crypto) {
globalThis.crypto = webcrypto;
}
import express from 'express';
import multer from 'multer';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import { v4 as uuidv4 } from 'uuid';
import path from 'path';
import fs from 'fs';
import { spawn } from 'child_process';
import { WebSocket as WS } from 'ws';
// Edge-TTS 需要的请求头
const EDGE_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0',
'Origin': 'chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
};
// 包装 WebSocket,自动添加 headers,并记录调试日志
class WrappedWebSocket extends WS {
constructor(url, protocols, options = {}) {
super(url, protocols, {
...options,
headers: { ...EDGE_HEADERS, ...(options.headers || {}) }
});
if (process.env.TTS_DEBUG === '1') {
console.log('[TTS-DEBUG] WebSocket connecting to:', url);
}
// 记录发送的消息
const originalSend = this.send.bind(this);
this.send = function(data, options, callback) {
if (process.env.TTS_DEBUG === '1') {
if (typeof data === 'string') {
// 输出 hex 以避免控制台编码问题
const buf = Buffer.from(data, 'utf8');
console.log('[TTS-DEBUG] SEND (text, hex):', buf.toString('hex'));
console.log('[TTS-DEBUG] SEND (text, len):', data.length, 'bytes:', buf.length);
} else {
console.log('[TTS-DEBUG] SEND (binary):', `[len=${data?.byteLength || data?.length}]`);
}
}
return originalSend(data, options, callback);
};
this.on('message', (data, isBinary) => {
if (process.env.TTS_DEBUG === '1') {
const tag = isBinary ? 'BINARY' : 'TEXT';
let preview;
if (isBinary) {
let bytes;
if (data instanceof ArrayBuffer) {
bytes = new Uint8Array(data);
} else if (ArrayBuffer.isView(data)) {
bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
} else {
bytes = new Uint8Array(data);
}
// 解析二进制消息的 header(前2字节是 header 长度)
let headerStr = '';
if (bytes.byteLength >= 2) {
const headerLen = bytes[0] << 8 | bytes[1];
const headerBytes = bytes.slice(2, 2 + headerLen);
headerStr = new TextDecoder().decode(headerBytes);
}
preview = `byteLen=${bytes.byteLength}, headerLen=${bytes.byteLength >= 2 ? (bytes[0] << 8 | bytes[1]) : 'N/A'}, header=\n${headerStr}`;
} else {
preview = data.toString().slice(0, 200);
}
console.log(`[TTS-DEBUG] ${tag} message:`, preview);
}
});
this.on('close', (code, reason) => {
if (process.env.TTS_DEBUG === '1') {
console.log('[TTS-DEBUG] WebSocket closed:', code, reason.toString());
}
});
this.on('error', (err) => {
if (process.env.TTS_DEBUG === '1') {
console.error('[TTS-DEBUG] WebSocket error:', err?.message || err);
}
});
this.on('open', () => {
if (process.env.TTS_DEBUG === '1') {
console.log('[TTS-DEBUG] WebSocket opened');
}
});
}
}
// 强制覆盖全局 WebSocket,让 @twn39/edgetts-js 使用 ws 包而非 Node.js 内置的
globalThis.WebSocket = WrappedWebSocket;
// 在 WebSocket 覆盖后加载 edgetts-js(使用 CJS 版本避免 ESM 兼容性问题)
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { Communicate } = require('@twn39/edgetts-js');
import https from 'https';
import { fileURLToPath } from 'url';
import pino from 'pino';
import authRoutes from './server/routes/auth.js';
import syncRoutes from './server/routes/sync.js';
import settingsRoutes from './server/routes/settings.js';
import { optionalAuth } from './server/middleware/auth.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const logger = pino({
level: process.env.LOG_LEVEL || 'info',
transport: process.env.NODE_ENV !== 'production' ? {
target: 'pino-pretty',
options: { colorize: true }
} : undefined,
});
const app = express();
const PORT = process.env.PORT || 3000;
const isDesktopMode = process.env.FUNLEARN_DESKTOP_MODE === '1';
const corsOrigins = (process.env.CORS_ORIGINS || 'http://localhost:5173').split(',').map(s => s.trim()).filter(Boolean);
// CORS:桌面模式允许任何 origin(因为前端是 Electron webview),
// 网络部署模式严格遵守白名单
app.use(cors({
origin: (origin, callback) => {
if (isDesktopMode) return callback(null, true);
if (!origin) return callback(null, true);
if (corsOrigins.includes(origin)) return callback(null, true);
// 允许 localhost 和 127.0.0.1(可选端口,Capacitor WebView 的 origin 无端口)
if (/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin)) return callback(null, true);
// 允许局域网 IP
if (/^http:\/\/192\.168\.\d+\.\d+(:\d+)?$/.test(origin)) return callback(null, true);
if (/^http:\/\/10\.\d+\.\d+\.\d+(:\d+)?$/.test(origin)) return callback(null, true);
if (/^http:\/\/172\.(1[6-9]|2\d|3[01])\.\d+\.\d+(:\d+)?$/.test(origin)) return callback(null, true);
callback(null, false);
},
}));
app.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
}));
const rateLimiter = rateLimit({
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW || '60000'),
max: parseInt(process.env.RATE_LIMIT_MAX || '60'),
message: { error: '请求过于频繁,请稍后再试' },
});
app.use('/api', rateLimiter);
app.use(express.json());
app.use((req, res, next) => {
const start = Date.now();
// 临时调试:记录 OPTIONS 和 auth 请求的 Origin
if (req.method === 'OPTIONS' || (req.path.startsWith('/api/auth') && req.method === 'POST')) {
console.log('[DEBUG]', req.method, req.path, 'Origin:', req.headers.origin, 'IP:', req.ip);
}
res.on('finish', () => {
const duration = Date.now() - start;
logger.info({
method: req.method,
path: req.path,
status: res.statusCode,
duration,
ip: req.ip,
});
});
next();
});
const uploadsDir = process.env.UPLOADS_DIR || path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, uploadsDir),
filename: (req, file, cb) => cb(null, `${uuidv4()}.wav`),
});
const ALLOWED_AUDIO_TYPES = ['audio/wav', 'audio/mpeg', 'audio/mp3', 'audio/webm', 'audio/ogg', 'audio/x-wav'];
const ALLOWED_EXTENSIONS = ['.wav', '.mp3', '.webm', '.ogg'];
const fileFilter = (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
if (ALLOWED_EXTENSIONS.includes(ext) || ALLOWED_AUDIO_TYPES.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('仅支持音频文件格式(wav/mp3/webm/ogg)'));
}
};
const upload = multer({
storage,
fileFilter,
limits: { fileSize: parseInt(process.env.UPLOAD_MAX_SIZE || '10485760') },
});
function getPythonCommand() {
return process.platform === 'win32' ? 'python' : 'python3';
}
function runAssessment(audioPath, expectedText, language) {
return new Promise((resolve, reject) => {
const pythonProcess = spawn(getPythonCommand(), [
path.join(__dirname, 'scripts', 'assess.py'),
'--audio', audioPath,
'--text', expectedText,
'--language', language,
]);
let stdout = '';
let stderr = '';
pythonProcess.stdout.on('data', (data) => {
stdout += data.toString();
});
pythonProcess.stderr.on('data', (data) => {
stderr += data.toString();
});
pythonProcess.on('close', (code) => {
if (code !== 0) {
reject(new Error(stderr || '评测脚本执行失败'));
return;
}
try {
const result = JSON.parse(stdout);
if (result.error) {
reject(new Error(result.error));
return;
}
resolve(result);
} catch {
reject(new Error('解析评测结果失败'));
}
});
});
}
app.use('/api/auth', authRoutes);
app.use('/api/sync', syncRoutes);
app.use('/api/settings', settingsRoutes);
// 健康检查缓存:每 60 秒刷新一次,避免每次请求都发起真实 TTS 连接
let cachedHealth = null;
let healthCacheTime = 0;
const HEALTH_CACHE_TTL = 60 * 1000;
app.get('/api/health', async (req, res) => {
const now = Date.now();
if (cachedHealth && now - healthCacheTime < HEALTH_CACHE_TTL) {
res.json({ ...cachedHealth, cached: true });
return;
}
const health = {
status: 'ok',
version: '1.0.0',
uptime: process.uptime(),
timestamp: new Date().toISOString(),
services: {
api: 'ok',
tts: 'unknown',
assessment: 'unknown',
},
};
try {
const communicate = new Communicate('测试', { voice: 'zh-CN-XiaoxiaoNeural' });
for await (const chunk of communicate.stream()) {
if (chunk.type === 'audio') break;
}
health.services.tts = 'ok';
} catch {
health.services.tts = 'degraded';
}
try {
const pythonCmd = process.platform === 'win32' ? 'python' : 'python3';
const check = spawn(pythonCmd, ['--version']);
await new Promise((resolve, reject) => {
check.on('close', (code) => code === 0 ? resolve() : reject());
check.on('error', reject);
});
health.services.assessment = 'ok';
} catch {
health.services.assessment = 'unavailable';
}
cachedHealth = health;
healthCacheTime = now;
res.json(health);
});
app.get('/api/voices', async (req, res) => {
try {
const url = 'https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list?trustedclienttoken=6A5AA1D4EAFF4E9FB37E23D68491D6F4';
https.get(url, (apiRes) => {
let data = '';
apiRes.on('data', (chunk) => { data += chunk; });
apiRes.on('end', () => {
try {
const voices = JSON.parse(data);
res.json(voices);
} catch (e) {
res.status(500).json({ error: '解析音色列表失败' });
}
});
}).on('error', (e) => {
logger.error({ err: e }, 'Direct fetch voices failed:');
res.status(500).json({ error: '获取音色列表失败' });
});
} catch (e2) {
res.status(500).json({ error: '获取音色列表失败' });
}
});
app.post('/api/tts', optionalAuth, async (req, res) => {
try {
const { text, voice, rate, pitch, volume, format } = req.body;
if (!text || !text.trim()) {
return res.status(400).json({ error: '请输入文本' });
}
if (process.env.TTS_DEBUG === '1') {
const textHex = Buffer.from(text, 'utf8').toString('hex');
console.log('[TTS-DEBUG] Received text:', JSON.stringify(text), 'hex:', textHex);
}
const communicateOptions = { voice: voice || 'zh-CN-XiaoxiaoNeural' };
if (rate) communicateOptions.rate = `${rate}%`;
if (pitch) communicateOptions.pitch = `${pitch}Hz`;
if (volume) communicateOptions.volume = `${volume}%`;
const communicate = new Communicate(text, communicateOptions);
const chunks = [];
for await (const chunk of communicate.stream()) {
if (chunk.type === 'audio') {
chunks.push(Buffer.isBuffer(chunk.data) ? chunk.data : Buffer.from(chunk.data));
}
}
const buffer = Buffer.concat(chunks);
if (buffer.length === 0) {
return res.status(500).json({ error: '语音合成失败:未生成音频数据' });
}
if (format === 'url') {
const filename = `tts_${Date.now()}_${Math.random().toString(36).slice(2)}.mp3`;
const filepath = path.join(uploadsDir, filename);
fs.writeFileSync(filepath, buffer);
const apiBase = process.env.API_BASE_URL || `${req.protocol}://${req.headers.host}`;
const audioUrl = `${apiBase}/uploads/${filename}`;
res.json({ url: audioUrl });
} else if (format === 'base64') {
// 返回 base64 编码的音频数据,供原生平台用 data URL 播放,避免 WebView HTTP 请求崩溃
const base64Audio = buffer.toString('base64');
res.json({ audio: `data:audio/mpeg;base64,${base64Audio}` });
} else {
res.setHeader('Content-Type', 'audio/mpeg');
res.setHeader('Content-Disposition', 'inline; filename="speech.mp3"');
res.send(buffer);
}
} catch (error) {
logger.error({ err: error }, 'TTS合成错误:');
res.status(500).json({ error: '语音合成失败: ' + error.message });
}
});
app.post('/api/assess', optionalAuth, upload.single('audio'), async (req, res) => {
try {
const { expectedText, language } = req.body;
const audioPath = req.file?.path;
if (!expectedText || !audioPath) {
return res.status(400).json({ error: '缺少必要参数' });
}
const result = await runAssessment(audioPath, expectedText, language || 'zh');
res.json({
success: true,
audioUrl: `/uploads/${req.file.filename}`,
...result,
});
} catch (error) {
logger.error({ err: error }, '评测错误:');
res.status(500).json({ error: '评测失败: ' + error.message });
}
});
app.delete('/api/audio/:filename', (req, res) => {
const filepath = path.join(uploadsDir, req.params.filename);
if (fs.existsSync(filepath)) {
fs.unlinkSync(filepath);
}
res.json({ success: true });
});
app.use('/uploads', express.static(uploadsDir));
function cleanOldUploads() {
try {
const files = fs.readdirSync(uploadsDir);
const now = Date.now();
const ONE_HOUR = 60 * 60 * 1000;
for (const file of files) {
const filepath = path.join(uploadsDir, file);
const stat = fs.statSync(filepath);
if (now - stat.mtimeMs > ONE_HOUR) {
fs.unlinkSync(filepath);
}
}
} catch {}
}
cleanOldUploads();
setInterval(cleanOldUploads, 10 * 60 * 1000);
// 桌面模式下仅监听 127.0.0.1(避免暴露到局域网),网络部署模式监听 0.0.0.0
const LISTEN_ADDR = isDesktopMode ? '127.0.0.1' : (process.env.LISTEN_ADDR || '0.0.0.0');
app.listen(PORT, LISTEN_ADDR, () => {
logger.info(`TTS服务已启动: http://${LISTEN_ADDR}:${PORT}${isDesktopMode ? ' (desktop mode)' : ''}`);
});