-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-https.js
More file actions
289 lines (250 loc) · 10.2 KB
/
server-https.js
File metadata and controls
289 lines (250 loc) · 10.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
const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const { Server } = require('socket.io');
const PORT = process.env.PORT || 3000;
const ROOM_HISTORY_LIMIT = 80;
const ROOM_TTL_MS = 1000 * 60 * 30; // 30 minutes
const app = express();
// 创建自签名证书 (开发环境用)
const selfsigned = require('selfsigned');
const attrs = [{ name: 'commonName', value: 'localhost' }];
const pems = selfsigned.generate(attrs, { days: 365 });
const httpsOptions = {
key: pems.private,
cert: pems.cert
};
const server = https.createServer(httpsOptions, app);
const io = new Server(server);
app.use(express.json());
// 静态文件服务 - 音频文件
app.use('/audio', express.static(path.join(__dirname, 'audio')));
// 静态文件服务 - 图片文件
app.use('/images', express.static(path.join(__dirname, 'images')));
const rooms = new Map();
function normalizeRoom(roomId = '') {
return roomId.trim().toUpperCase();
}
function ensureRoom(roomId) {
const normalized = normalizeRoom(roomId);
if (!normalized) return null;
if (!rooms.has(normalized)) {
rooms.set(normalized, { users: new Map(), messages: [], cleanupTimer: null });
}
const room = rooms.get(normalized);
if (room.cleanupTimer) {
clearTimeout(room.cleanupTimer);
room.cleanupTimer = null;
}
return room;
}
function roomSnapshot(roomId) {
const normalized = normalizeRoom(roomId);
const room = rooms.get(normalized);
if (!room) {
return { roomId: normalized, participants: [], messages: [] };
}
return {
roomId: normalized,
participants: Array.from(room.users.values()).map((user) => ({
id: user.socketId,
name: user.name,
joinedAt: user.joinedAt,
cameraOn: !!user.cameraOn,
status: user.status || null,
})),
messages: room.messages,
};
}
function sanitizeStatus(input = {}) {
if (!input || typeof input !== 'object') {
return { text: '', visible: false, updatedAt: Date.now() };
}
const visible = input.visible !== false;
const safeText = typeof input.text === 'string' ? input.text.slice(0, 80) : '';
const safe = {
text: visible ? safeText : '',
visible,
manual: typeof input.manual === 'string' ? input.manual.slice(0, 40) : '',
manualPreset: typeof input.manualPreset === 'string' ? input.manualPreset : null,
autoSync: !!input.autoSync,
ambientType: typeof input.ambientType === 'string' ? input.ambientType.slice(0, 20) : null,
timerMode: input.timerMode === 'break' ? 'break' : (input.timerMode === 'focus' ? 'focus' : null),
updatedAt: typeof input.updatedAt === 'number' ? input.updatedAt : Date.now(),
};
return safe;
}
function scheduleRoomCleanup(roomId) {
const room = rooms.get(roomId);
if (!room || room.users.size > 0 || room.cleanupTimer) return;
room.cleanupTimer = setTimeout(() => rooms.delete(roomId), ROOM_TTL_MS);
}
function createSystemMessage(text, username = '', action = '') {
return {
id: `sys-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
author: 'system',
text,
username,
action,
timestamp: Date.now(),
type: 'system',
};
}
app.get('/api/rooms/:roomId', (req, res) => {
const { roomId } = req.params;
if (!roomId) return res.status(400).json({ error: 'Room id missing' });
const snapshot = roomSnapshot(roomId);
if (!rooms.has(normalizeRoom(roomId))) {
return res.status(404).json({ error: 'Room not found' });
}
return res.json(snapshot);
});
app.get('/', (_req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', (socket) => {
socket.on('join-room', (payload = {}, ack = () => {}) => {
const { roomId, username } = payload;
const cleanName = (username || '').trim();
const normalizedRoom = normalizeRoom(roomId);
if (!cleanName) {
return ack({ ok: false, error: '请填写昵称' });
}
if (!normalizedRoom) {
return ack({ ok: false, error: '房间号缺失' });
}
const room = ensureRoom(normalizedRoom);
room.users.set(socket.id, {
socketId: socket.id,
name: cleanName,
joinedAt: Date.now(),
cameraOn: false,
status: null,
});
socket.data.username = cleanName;
socket.data.roomId = normalizedRoom;
socket.join(normalizedRoom);
const snapshot = roomSnapshot(normalizedRoom);
ack({ ok: true, room: snapshot });
io.to(normalizedRoom).emit('presence', snapshot.participants);
const systemMsg = createSystemMessage(`${cleanName} joined the room`, cleanName, 'join');
room.messages.push(systemMsg);
if (room.messages.length > ROOM_HISTORY_LIMIT) room.messages.shift();
io.to(normalizedRoom).emit('chat-message', systemMsg);
});
socket.on('send-message', (payload = {}, ack = () => {}) => {
const { text } = payload;
const currentRoom = socket.data.roomId;
const cleanText = (text || '').trim();
if (!currentRoom) {
return ack({ ok: false, error: '尚未加入房间' });
}
if (!cleanText) {
return ack({ ok: false, error: '消息不能为空' });
}
const room = ensureRoom(currentRoom);
const message = {
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
author: socket.data.username,
text: cleanText,
timestamp: Date.now(),
type: 'user',
};
room.messages.push(message);
if (room.messages.length > ROOM_HISTORY_LIMIT) room.messages.shift();
io.to(currentRoom).emit('chat-message', message);
ack({ ok: true });
});
socket.on('camera-status', (payload = {}) => {
const { roomId } = socket.data;
if (!roomId) return;
const room = rooms.get(roomId);
if (!room) return;
const user = room.users.get(socket.id);
if (!user) return;
user.cameraOn = !!payload.camera;
io.to(roomId).emit('camera-status', { userId: socket.id, camera: user.cameraOn });
});
socket.on('rtc-offer', (payload = {}) => {
const { roomId } = socket.data;
const { targetId, sdp } = payload;
if (!roomId || !targetId || !sdp) return;
const room = rooms.get(roomId);
if (!room || !room.users.has(targetId)) return;
io.to(targetId).emit('rtc-offer', { from: socket.id, sdp });
});
socket.on('rtc-answer', (payload = {}) => {
const { roomId } = socket.data;
const { targetId, sdp } = payload;
if (!roomId || !targetId || !sdp) return;
const room = rooms.get(roomId);
if (!room || !room.users.has(targetId)) return;
io.to(targetId).emit('rtc-answer', { from: socket.id, sdp });
});
socket.on('rtc-ice', (payload = {}) => {
const { roomId } = socket.data;
const { targetId, candidate } = payload;
if (!roomId || !targetId || !candidate) return;
const room = rooms.get(roomId);
if (!room || !room.users.has(targetId)) return;
io.to(targetId).emit('rtc-ice', { from: socket.id, candidate });
});
socket.on('user-status', (payload = {}, ack = () => {}) => {
const { status } = payload || {};
const { roomId } = socket.data;
if (!roomId) return ack({ ok: false });
const room = rooms.get(roomId);
if (!room) return ack({ ok: false });
const user = room.users.get(socket.id);
if (!user) return ack({ ok: false });
const safeStatus = sanitizeStatus(status);
user.status = safeStatus;
io.to(roomId).emit('status-update', { userId: socket.id, status: safeStatus });
ack({ ok: true });
});
socket.on('disconnect', () => {
const { roomId } = socket.data;
if (!roomId) return;
const room = rooms.get(roomId);
if (!room) return;
const user = room.users.get(socket.id);
room.users.delete(socket.id);
io.to(roomId).emit('camera-status', { userId: socket.id, camera: false });
const snapshot = roomSnapshot(roomId);
io.to(roomId).emit('presence', snapshot.participants);
if (user) {
const systemMsg = createSystemMessage(`${user.name} left the room`, user.name, 'leave');
room.messages.push(systemMsg);
if (room.messages.length > ROOM_HISTORY_LIMIT) room.messages.shift();
io.to(roomId).emit('chat-message', systemMsg);
}
scheduleRoomCleanup(roomId);
});
});
const os = require('os');
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return 'localhost';
}
server.listen(PORT, () => {
const localIP = getLocalIP();
console.log(`
╔════════════════════════════════════════════════════════╗
║ Co-Study HTTPS Server Started! 🎉 ║
╠════════════════════════════════════════════════════════╣
║ 本地访问: https://localhost:${PORT} ║
║ 手机访问: https://${localIP}:${PORT} ║
╠════════════════════════════════════════════════════════╣
║ ⚠️ 首次访问会提示"不安全",点击"高级" → "继续访问" ║
║ 这是因为使用了自签名证书(仅用于开发测试) ║
╚════════════════════════════════════════════════════════╝
`);
});