-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
163 lines (136 loc) · 4.68 KB
/
server.js
File metadata and controls
163 lines (136 loc) · 4.68 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
require('dotenv').config();
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cors = require('cors');
const tencentcloud = require("tencentcloud-sdk-nodejs-trtc");
const TLSSigAPIv2 = require('tls-sig-api-v2');
const TrtcClient = tencentcloud.trtc.v20190722.Client;
// TRTC配置
const trtcConfig = {
secretId: process.env.TENCENT_SECRET_ID,
secretKey: process.env.TENCENT_SECRET_KEY,
region: process.env.TENCENT_REGION || 'ap-guangzhou',
endpoint: process.env.TENCENT_ENDPOINT || 'trtc.tencentcloudapi.com',
sdkAppId: parseInt(process.env.TRTC_SDK_APP_ID || '0'),
sdkSecretKey: process.env.TRTC_SECRET_KEY, // 用于生成UserSig
expireTime: 86400
};
const app = express();
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
app.use(express.json());
app.use(cors());
app.use(express.static(path.join(__dirname, 'public'), {
maxAge: '1m',
etag: true,
setHeaders: (res, path) => {
if (path.endsWith('.html')) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
}
}
}));
/**
* Create a new TRTC client instance
* @returns {Object} New TRTC client instance
*/
function createTrtcClient() {
if (!trtcConfig.secretId || !trtcConfig.secretKey) {
throw new Error('TRTC configuration missing. Please set environment variables.');
}
console.log('Creating new TRTC client');
return new TrtcClient({
credential: {
secretId: trtcConfig.secretId,
secretKey: trtcConfig.secretKey,
},
region: trtcConfig.region,
profile: {
httpProfile: {
endpoint: trtcConfig.endpoint,
},
},
});
}
/**
* Generate user credentials for TRTC
* POST /credentials
*/
app.post('/credentials', (req, res) => {
try {
const { sdkAppId, sdkSecretKey, expireTime } = trtcConfig;
if (!sdkAppId || !sdkSecretKey) {
return res.status(400).json({
error: 'TRTC configuration missing. Please set environment variables: SDK_APP_ID, TENCENT_SECRET_KEY'
});
}
const randomNum = Math.floor(100000 + Math.random() * 900000).toString();
const userId = `user_${randomNum}`;
const robotId = `ai_${randomNum}`;
const roomId = parseInt(randomNum);
const api = new TLSSigAPIv2.Api(sdkAppId, sdkSecretKey);
const userSig = api.genSig(userId, expireTime);
const robotSig = api.genSig(robotId, expireTime);
const credentials = { sdkAppId, userSig, robotSig, userId, robotId, roomId };
res.json(credentials);
} catch (error) {
console.error('Failed to generate user information', error);
return res.status(500).json({ error: error.message });
}
});
/**
* Start simultaneous interpretation using transcription API
* POST /interpretation
*/
app.post('/interpretation', async (req, res) => {
try {
const { ...requestData } = req.body;
// Validate required parameters
if (!requestData.SdkAppId || !requestData.RoomId) {
return res.status(400).json({
error: 'Missing required parameters: SdkAppId, RoomId'
});
}
const client = createTrtcClient();
console.log('🌐 Starting simultaneous interpretation:', JSON.stringify(requestData, null, 2));
const result = await client.StartAITranscription(requestData);
console.log('✅ Simultaneous interpretation started:', JSON.stringify(result, null, 2));
res.json({
TaskId: result.TaskId,
userInfo: {
sdkAppId: requestData.SdkAppId,
roomId: requestData.RoomId,
userId: requestData.TranscriptionParams?.UserId,
userSig: requestData.TranscriptionParams?.UserSig,
robotId: requestData.TranscriptionParams?.TargetUserId
}
});
} catch (error) {
console.error('❌ Error starting interpretation:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Stop simultaneous interpretation
* DELETE /interpretation
*/
app.delete('/interpretation', async (req, res) => {
try {
const { TaskId } = req.body;
if (!TaskId) {
return res.status(400).json({
error: 'Missing required field: TaskId'
});
}
const client = createTrtcClient();
console.log('🛑 Stopping interpretation:', { TaskId });
const data = await client.StopAITranscription({ TaskId });
console.log('✅ Interpretation stopped successfully');
res.json(data);
} catch (error) {
console.error('❌ Interpretation stop failed:', error.message);
res.status(500).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '127.0.0.1';
app.listen(PORT, HOST, () => console.log(`App running at http://${HOST}:${PORT}/`));